Chapter 2 Basics
2.1 Order of Execution
FROMclause
SQL begins by identifying and combining all relevant data from the specified tables. This includes any joins or subqueries. The FROM clause defines the data source and sets the foundation for the rest of the query.
JOINclause
If there are any JOIN clauses, SQL processes them immediately after identifying the tables in the FROM clause. The joining of tables determines which rows from the combined tables are considered for further steps.
WHEREclause
After combining tables, SQL applies the WHERE clause to filter out rows that do not meet the criteria. The result is a reduced dataset that satisfies the condition(s).
GROUP BYclause
SQL groups the filtered rows based on the columns specified in the GROUP BY clause. This is necessary for aggregate functions like COUNT, SUM, AVG, etc.
HAVINGorQUALIFYclause
After the
GROUP BYclause, SQL applies theHAVINGclause to filter the grouped results. UnlikeWHERE, which filters rows before grouping,HAVINGfilters groups after they have been formed.The window functions like
RANK()are executed before filtering byQUALIFY.TheQUALIFYclause then filters based on the results of these window functions.SELECTAfterQUALIFY: TheSELECTclause is applied last, selecting the columns from the result set after the filtering is done byQUALIFY.
SELECTclause
SQL evaluates the SELECT clause after all filtering, grouping, and having conditions have been applied. It determines which columns or expressions are included in the final output.
DISTINCTclause
SQL applies the DISTINCT clause after the SELECT clause, ensuring that only unique rows are returned.
ORDER BYclause
SQL orders the final result set according to the columns specified in the ORDER BY clause. This is the last step in query execution before the result set is returned.
LIMIT-OFFSET-TOP
SQL applies these clauses after all other operations have been completed. LIMIT defines how many rows to return, while OFFSET skips a specified number of rows.