Oracle SQL clause evaluation order
In Oracle, which clause types get evaluated first? If I had the following ( pretend .... represent valid expressions and relation names ), what would the order of evaluation be?
SELECT ...
FROM .....
WHERE ........
GROUP BY ...........
HAVING .............
ORDER BY ................
I am under the impression that the SELECT clause is evaluated l开发者_运维问答ast, but other than that I'm clueless.
The select list cannot always be evaluated last because the ORDER BY can use aliases that are defined in the select list so they must be executed afterwards. For example:
SELECT foo+bar foobar FROM table1 ORDER BY foobar
I'd say that in general the order of execution could be something like this:
- FROM
- WHERE
- GROUP BY
- SELECT
- HAVING
- ORDER BY
The GROUP BY and the WHERE clauses could be swapped without changing the result, as could the HAVING and ORDER BY.
In reality things are more complex because the database can reorder the execution according to different execution plans. As long as the result remains the same it doesn't matter in what order it is executed.
Note also that if an index is chosen for the ORDER BY clause the rows could already be in the correct order when they are read from disk. In this case the ORDER BY clause isn't really executed at all.
That's what execution plans are for. But, generally, there's only 1 way to do it. I'll ignore optimizations for the moment:
- FROM to get the table involved
- Start scanning the table in FROM, keeping those that pass WHERE clause
- SELECT unaggregated columns
- Calculate aggregated columns with GROUP BY
- Keep those grouped results that pass HAVING clause
- order results with ORDER BY
Optimizations could cause some "peeking" to make better decisions (eg., it'd be a good idea to check the WHERE clause before scanning the table - an index may be available).
I believe most RDBMS solve this with a pre-pass through an optimizer which will basically rewrite the query to take advantage of indexes, remove redundant expressions, etc. This optimized query is then used to actually build the execution plan. There's also parallelism that could change the specifics - but the basics are the same.
Oracle Query Processing Order
- FROM clause
- WHERE clause
- GROUP BY clause
- HAVING clause
- SELECT clause
- ORDER BY clause
Below is SQL Query Processing Order:
FROM
CONNECT BY
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Logical Processing Order of the SELECT
statement
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE or WITH ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
This is the logical order to be used in writing/(logically thinking out) the query. The database may optimize the query in different ways during actual execution for sake of efficiency, as long as the returned results are the same as if it followed this execution order.
References
Microsoft T-SQL
Oracle Blog
精彩评论