Organizational Research By

Surprising Reserch Topic

oracle sql clause evaluation order

oracle sql clause evaluation order  using -'sql,oracle,clause,order-of-evaluation'

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 last, but other than that I'm clueless.

asked Sep 21, 2015 by rajesh
0 votes

Related Hot Questions

2 Answers

0 votes

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

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.

answered Sep 21, 2015 by nimisha.jagtap
0 votes

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.

answered Sep 21, 2015 by mannumits1