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
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:
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.
Oracle Query Processing Order
Below is SQL Query Processing Order:
FROM
CONNECT BY
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Logical Processing Order of the SELECT
statement
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
That's what execution plans are for. But, generally, there's only 1 way to do it. I'll ignore optimizations for the moment:
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.