Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the execute order of the different parts of a SQL select statement?

Tags:

sql

What's the execute order of the different parts of a SQL select statement? Such as
distinct
from
order by
group by
having
multiline function(count, avg, max, min...)
top(sql server) or limit(mysql)
other parts

Does the different databases have the same execution order? Great thanks.

like image 584
Just a learner Avatar asked Apr 11 '10 16:04

Just a learner


2 Answers

Have a look at

SQL SERVER – Logical Query Processing Phases – Order of Statement Execution

  1. FROM
  2. ON
  3. OUTER
  4. WHERE
  5. GROUP BY
  6. CUBE | ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Also, for some good info see Logical Query Processing

like image 145
Adriaan Stander Avatar answered Nov 02 '22 00:11

Adriaan Stander


The above answer addresses the question but there is one exception to the above mentioned order

when you have

select top n ............

order by

Then, order by will be executed before select. ( the entries are ordered first and then the top n entries are selected)

like image 33
Naga Avatar answered Nov 02 '22 00:11

Naga