SQL's declarative syntax often creates an illusion: we start a query with the SELECT keyword, listing the columns we want. Yet in the PostgreSQL Query Path documentation, the logical execution pipeline is wired differently.
The relational engine processes a query in this chain:
FROMandJOIN: base table reads and joins;WHERE: filtering rows before aggregations;GROUP BYandHAVING: grouping and filtering groups;SELECT: evaluating expressions and assigning aliases;DISTINCT,ORDER BY, andLIMIT: deduplication, sorting, and slicing.
That is why trying to reference a SELECT alias inside a WHERE clause fails with an error:
-- ERROR: column "bonus" does not exist
SELECT salary * 0.2 AS bonus
FROM employees
WHERE bonus > 1000;
At step 2, the engine has not reached the SELECT projection (step 4) yet and does not know the name bonus.
As we noted in our breakdown of SQL execution order, the fix is simple: repeat the expression or move it into a CTE:
WITH payroll AS (
SELECT id, salary * 0.2 AS bonus FROM employees
)
SELECT * FROM payroll WHERE bonus > 1000;
