Logical Execution Order of a SQL Query: Why SELECT Runs Second to LastBrief · digest for October 19
Brief≈ 1 min

Logical Execution Order of a SQL Query: Why SELECT Runs Second to Last

SQL syntax is deceptive: a query starts with SELECT, yet the database's logical pipeline runs in a completely different order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY -> LIMIT.

That's why a computed alias isn't available inside a WHERE filter:

-- ERROR: gross_revenue has not been computed yet at the WHERE stage
SELECT product_id, unit_price * quantity AS gross_revenue
FROM sales_records
WHERE gross_revenue > 5000;

During WHERE, SELECT expressions don't exist in scope yet. In ORDER BY, however, the alias works right away—and to filter on it cleanly, just wrap it in a CTE:

-- Clean workaround using a CTE
WITH calculated AS (
    SELECT product_id, unit_price * quantity AS gross_revenue
    FROM sales_records
)
SELECT product_id, gross_revenue
FROM calculated
WHERE gross_revenue > 5000
ORDER BY gross_revenue DESC;

As we covered in SQL Execution Order: Why Syntax Is Deceptive and How to Use It for Optimization, knowing this stage sequence saves you from alias bugs and encourages filtering out extra rows as early as possible.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2