The order of SQL execution
2024
The order of SQL execution follows a specific logical sequence, regardless of how the SQL query is written. Here’s the general execution order of SQL clauses:
- FROM – This is the first step where the tables or views are identified and joined (if applicable).
- ON – If you’re using
JOIN
, theON
condition is evaluated to establish how the tables are joined. - WHERE – Filters the rows based on the condition provided.
- GROUP BY – Groups the result set by one or more columns.
- HAVING – Filters the results after the grouping has been applied (like
WHERE
, but it works on aggregated results). - SELECT – After grouping and filtering, the columns specified in the
SELECT
clause are determined. - DISTINCT – Removes duplicate rows from the results (if specified).
- ORDER BY – Sorts the results based on the specified columns.
- LIMIT / OFFSET – Limits the number of rows returned (if applicable).
Visualizing the SQL Execution Order:
sqlCopy codeSELECT column_list
FROM table
JOIN another_table ON condition
WHERE condition
GROUP BY column
HAVING condition
ORDER BY column
LIMIT number;
- 1. FROM: Start by determining which tables to use.
- 2. ON: If
JOIN
is used, establish the join condition. - 3. WHERE: Apply filters to rows.
- 4. GROUP BY: Group rows into aggregate sets.
- 5. HAVING: Apply conditions to the grouped results.
- 6. SELECT: Choose the columns to include in the final output.
- 7. DISTINCT: Remove duplicates (if used).
- 8. ORDER BY: Sort the results.
- 9. LIMIT/OFFSET: Restrict the number of rows returned.
Example:
sqlCopy codeSELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 1
ORDER BY employee_count DESC;
Execution Order:
- FROM:
employees
table is accessed. - WHERE: Only employees with a salary greater than 50,000 are considered.
- GROUP BY: The remaining rows are grouped by
department
. - HAVING: Only departments with more than one employee are included.
- SELECT: The
department
andemployee_count
are selected. - ORDER BY: Results are ordered by
employee_count
in descending order.
Understanding this order helps in writing correct and efficient SQL queries.