Part 02 / Topic 9 of 9
How a query is evaluated
You write SELECT first, but Postgres evaluates it late. The logical order:
FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT
(GROUP BY and HAVING join the party in Part 4.) This single fact explains the most famous beginner error — using a SELECT alias inside WHERE:
SELECT name, price * stock AS shelf_value
FROM products
WHERE shelf_value > 10000;
ERROR: column "shelf_value" does not exist
LINE 3: WHERE shelf_value > 10000;
^
WHERE runs before SELECT, so at filter time shelf_value doesn't exist yet. Repeat the expression (or use a subquery — Stage 2):
SELECT name, price * stock AS shelf_value
FROM products
WHERE price * stock > 10000;
name | shelf_value
---------------+-------------
Laptop Pro 14 | 18000.00
Phone X | 19975.00
Phone Lite | 15960.00
(3 rows)
But ORDER BY shelf_value DESC would work — ORDER BY runs after SELECT, so it sees aliases. The evaluation order isn't trivia; it predicts exactly which names exist where.
🧪 Quick quiz — answer from memory, then check.
SELECT name AS n FROM products WHERE n = 'Phone X';— what happens?- Why can ORDER BY use a SELECT alias when WHERE cannot?
Show the answers
ERROR: column "n" does not exist— WHERE is evaluated before SELECT creates the alias.- ORDER BY runs after SELECT in the logical order, so the alias exists by then.
Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.