问题
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