What is the logical evaluation order of a SELECT query?
MédioMost engines evaluate a query roughly in this order: FROM and JOIN first, then WHERE, then GROUP BY, then HAVING, then the SELECT list, then ORDER BY and LIMIT.
SELECT city, COUNT(*) AS customers -- 5. SELECT
FROM customers -- 1. FROM / JOIN
WHERE signup_date >= '2025-01-01' -- 2. WHERE
GROUP BY city -- 3. GROUP BY
HAVING COUNT(*) > 10 -- 4. HAVING
ORDER BY customers DESC -- 6. ORDER BY
The practical consequence: a column alias defined in the SELECT list cannot be used in WHERE, because WHERE runs first. Every engine accepts the alias in ORDER BY, which runs last. HAVING is where engines split: MySQL and SQLite accept a SELECT alias there as an extension, while PostgreSQL and SQL Server make you repeat the expression. Window functions and DISTINCT are evaluated with the SELECT list, which is why a window function cannot appear in WHERE either.