12

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.

Just a learner
  • 26,690
  • 50
  • 155
  • 234
  • Possible duplicate of [Order Of Execution of the SQL query](https://stackoverflow.com/questions/4596467/order-of-execution-of-the-sql-query) – rsjaffe Nov 05 '18 at 03:55
  • I asked at 2010-04-11, the question you mentioned is asked at 2011-01-04. Why not say that question is a duplication of mine? @rsjaffe – Just a learner Nov 05 '18 at 03:57
  • Because the other has better answers. The goal of duplicate flags is to use each duplicate question as a guidepost for some one searching the issue, but then send them to the place where the authoritative answers are. – rsjaffe Nov 05 '18 at 04:57
  • See https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled for more discussion on selecting which to close. – rsjaffe Nov 05 '18 at 05:00

2 Answers2

19

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

Just a learner
  • 26,690
  • 50
  • 155
  • 234
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • Where does UNION fit into this order? – Walter Mitty Aug 09 '13 at 13:07
  • @WalterMitty I know you asked your question a very long time ago, but `UNION` and `UNION ALL` are ways to join two separate queries together, so the above would happen for the first query, then the second query, then the `UNION` of the two results would be performed. – Ryan Guill May 15 '17 at 15:05
2

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)

Naga
  • 141
  • 1
  • 12