Why it happens: the alias does not work in WHERE
SELECT id,
unit_price * quantity AS total
FROM order_items
WHERE total > 100;The alias total belongs to the output list. In PostgreSQL and MySQL, WHERE needs to work with the available columns and expressions before producing that list.
Check the result with small data
First, the subtotal alias is calculated inside an inner query.
WITH sales(price, quantity) AS (VALUES (8,2),(3,1))
SELECT subtotal FROM (
SELECT price * quantity AS subtotal FROM sales
) AS calculations WHERE subtotal > 10;| subtotal |
|---|
| 16 |
The outer SELECT can now filter on it because the subquery exposes subtotal as a column of its result. Repeating price*quantity in WHERE is also a portable solution.
Check your understanding: Which row disappears with a threshold of 10?
Show answer
The one with price 3 and quantity 1: its subtotal is 3, which does not exceed 10. Only the one with 16 remains.
How to fix it in SQL
Fix 1: repeat the expression when it is simple
SELECT id,
unit_price * quantity AS total
FROM order_items
WHERE unit_price * quantity > 100;For a short expression, this form is clear and portable. The alias is still useful for naming the resulting column.
Fix 2: add a layer when the expression is complex
If repeating the expression makes the query hard to read, calculate the alias first in a subquery or CTE. In the outer query, total is already a column of the virtual table produced by the inner query:
SELECT id, total
FROM (
SELECT id,
unit_price * quantity AS total
FROM order_items
) AS calculations
WHERE total > 100;How to check it
Test the query with the full expression and compare the rows before adding more conditions.
How to avoid it next time
An alias names an output; it does not change the logical order of the query.
Related cases worth checking
SQLite, the lab engine, accepts this query as its own extension: if you try it here, it will work. Do not treat it as portable: PostgreSQL, MySQL and SQL Server reject it because an output alias cannot be used directly in WHERE. For a query that works across engines, use the original expression or an intermediate layer.