Let's learn about the execution order of SELECT queries.
Reference: SQL BOLT
SELECTcolumn nameFROMtable nameWHEREconditionGROUP BYcolumn nameHAVINGconditionORDER BYcolumn name
FROMONJOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BY
JOINis executed first to collect the data set- This operation includes subqueries, creating a temporary table that contains all JOINed rows and columns
- Once the data set is formed, the conditions in
WHEREare applied to each row - The constraints in the
WHEREclause are applied to the tables requested in theFROMclause
- After the
WHEREclause is applied, the remaining rows are grouped based on common values in the columns specified in theGROUP BYclause - When using a
GROUP BYclause, you can use aggregate functions on those columns
- If there is a
GROUP BYclause in the query, the constraints in theHAVINGclause are applied to the grouped rows - Changing the conditions in the
HAVINGclause does not change the result data, only the number of output records
- The
SELECTclause is executed last
- Among the remaining rows, rows with duplicate column values are deleted
- The 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