SQL query, sequence of execution

百般思念 提交于 2020-01-01 18:18:28

问题


What will be the sequence of execution followed by SQL if a query has both group by and order by clause. Does it depend on their position in the query???


回答1:


ORDER BY always executes on the results of the grouping performed by GROUP BY, i.e., always "after". In standard SQL, you must have ORDER BY lexically after GROUP BY, if both are present, to kind of "remind you" of the fact.




回答2:


in order:

FROM & JOINs determine & filter rows
WHERE more filters on the rows
GROUP BY combines those rows into groups
HAVING filters groups
ORDER BY arranges the remaining rows/groups




回答3:


It depends on many things including the RDMS you are using. The best way to find out what is going on is to use a query tool that allows you to see the query execution plan.




回答4:


Order by generally happens last.

If you're using SQL Server, fire up query analyzer and execution plan will give you a nice graphical representation of your query.




回答5:


The sequence of execution is not mandated by any SQL statement. What is mandated is that the result match the result that would be obtained by a "canonical" evaluation. In the canonical evaluation, the ORDER BY is applied last (even after the SELECT list expressions are evaluated), but that doesn't mean sorting is postponed to that point in the actual execution of a query on a real system.




回答6:


group by gets executed first and then the results of the group are ordered.




回答7:


Let's assume we have SQL query:

SELECT   ...
  FROM     ...
  WHERE    ...
  GROUP BY ...
  HAVING   ...
  ORDER BY ...

the order in which sub-clauses of SQL query are executed is:

 1. FROM clause
 2. WHERE clause
 3. GROUP BY clause
 4. HAVING clause
 5. SELECT clause
 6. ORDER BY clause



回答8:


I will also suggest using a query analyzer for the specific database engine. The following is an example in Postgres, which explains that ORDER BY is executed first and after that the WHERE filter:

EXPLAIN
SELECT * FROM table WHERE id=x AND date<='yyyy-mm-dd' ORDER BY date DESC;

So if I alter DESC to ASC the result set will contain different records!



来源:https://stackoverflow.com/questions/1454800/sql-query-sequence-of-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!