Order of Execution

Written Order vs Logical Order

You write a query in one order, but the database evaluates it in another. Knowing the logical order explains many errors.

StepClauseWhat happens
1FROM / JOINpick the tables and combine them
2WHEREfilter rows
3GROUP BYform groups
4HAVINGfilter groups
5SELECTcompute output columns and aliases
6DISTINCTremove duplicate rows
7ORDER BYsort
8LIMIT / OFFSETcut the result

Why It Matters

  • A column alias defined in SELECT cannot be used in WHERE (WHERE runs first), but it can be used in ORDER BY.
  • Aggregates cannot appear in WHERE, because groups do not exist yet. Use HAVING.
  • LIMIT runs last, so it limits the final, sorted result.

Example

The alias Total works in ORDER BY:

SELECT CustomerID, SUM(Amount) AS Total
FROM Orders
GROUP BY CustomerID
ORDER BY Total DESC;

Result: 6 rows

CustomerIDTotal
2412
3320.75
1301.75
7198.4
5150
4116.9

Exercise

Exercise: For each department, show the average salary rounded to 0 decimals, only for departments whose average is above 60000, highest first.

Show answer
SELECT Department, ROUND(AVG(Salary), 0) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000
ORDER BY AvgSalary DESC;