Chapter 2 Basics
2.1 Order of Execution
FROM
clause
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.
JOIN
clause
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.
WHERE
clause
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 BY
clause
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.
HAVING
orQUALIFY
clause
After the
GROUP BY
clause, SQL applies theHAVING
clause to filter the grouped results. UnlikeWHERE
, which filters rows before grouping,HAVING
filters groups after they have been formed.The window functions like
RANK()
are executed before filtering byQUALIFY.
TheQUALIFY
clause then filters based on the results of these window functions.SELECT
AfterQUALIFY
: TheSELECT
clause is applied last, selecting the columns from the result set after the filtering is done byQUALIFY.
SELECT
clause
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.
DISTINCT
clause
SQL applies the DISTINCT
clause after the SELECT
clause, ensuring that only unique rows are returned.
ORDER BY
clause
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.