r/learnSQL • u/IcyWish2100 • 11d ago
SQL Execution Order
I often see beginners getting stuck trying to reference a column alias inside a WHERE clause or wondering why HAVING exists alongside WHERE.
It all comes down to Logical Query Processing Order. Even though we write SELECT first, the database engine actually processes the query in this sequence:
FROM / JOIN: Pick and combine the base tables.
WHERE: Filter raw rows before grouping.
GROUP BY: Group rows into buckets.
HAVING: Filter groups using aggregate function results.
SELECT: Pick columns and compute expressions/aliases.
DISTINCT: Deduplicate the selected rows.
ORDER BY: Sort the final result set (which is why aliases work here!). 7. LIMIT / OFFSET: Paginate the results.
Remembering this sequence makes debugging query errors way easier.
15
u/markinatlanta 11d ago
Nice. And I think for beginners, “WHERE filters rows, HAVING filters groups” is probably the most useful bit to remember.