SQL Order of Operations
Let's learn about the execution order of SELECT queries.
Reference: SQL BOLT
Syntax Order
SELECTcolumn nameFROMtable nameWHEREconditionGROUP BYcolumn nameHAVINGconditionORDER BYcolumn name
Execution Order
FROMONJOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BY
Detailed Look at Execution Order
1. FROM and JOINs
FROM and JOINsJOINis executed first to collect the data setThis operation includes subqueries, creating a temporary table that contains all JOINed rows and columns
2. WHERE
WHEREOnce the data set is formed, the conditions in
WHEREare applied to each rowThe constraints in the
WHEREclause are applied to the tables requested in theFROMclause
3. GROUP BY
GROUP BYAfter the
WHEREclause is applied, the remaining rows are grouped based on common values in the columns specified in theGROUP BYclauseWhen using a
GROUP BYclause, you can use aggregate functions on those columns
4. HAVING
HAVINGIf there is a
GROUP BYclause in the query, the constraints in theHAVINGclause are applied to the grouped rowsChanging the conditions in the
HAVINGclause does not change the result data, only the number of output records
5. SELECT
SELECTThe
SELECTclause is executed last
6. DISTINCT
DISTINCTAmong the remaining rows, rows with duplicate column values are deleted
7.ORDER BY
ORDER BYThe stored values are sorted in ascending or descending order
Since the
SELECTclause of the query has already been executed, aliases can be referenced in theORDER_BYclause
Last updated