SQL query, sequence of execution

痞子三分冷 提交于 2019-12-04 15:39:06

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.

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

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.

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.

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.

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

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

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!

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