Logical order of execution

The logical order of execution of a query differs from the order it is written in: FROM and joins, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, then LIMIT. It explains why a SELECT alias cannot be used in WHERE, but can be used in ORDER BY. The engine may optimize the actual execution without changing the result.

Example

FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT

Related concepts

The whole glossary