SQL error
column "age_months" does not exist (using an alias in WHERE)
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
SQL evaluates WHERE before SELECT, so an alias you create in SELECT doesn't exist yet when WHERE runs. Repeat the expression, or compute it in a subquery or CTE first.
The exact messages
- PostgreSQLERROR: column "age_months" does not exist
- SQLiteNo error, but a silent surprise: see below.
How to read this message
This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.
ERROR: column "age_months" does not exist
LINE 3: WHERE age_months > 50;
^Why it happens
Filtering on a calculated alias
The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. Aliases only become visible from ORDER BY onwards.
The same thing in HAVING
HAVING n > 2 where n is a COUNT(*) AS n alias fails in PostgreSQL for the same reason. Write HAVING COUNT(*) > 2.
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
SELECT name, age * 12 AS age_months
FROM pets
WHERE age_months > 50;SELECT name, age * 12 AS age_months
FROM pets
WHERE age * 12 > 50;Repeating the expression is the simplest fix. For long expressions, compute it once in a CTE: WITH t AS (SELECT name, age * 12 AS age_months FROM pets) SELECT * FROM t WHERE age_months > 50;
The fix returns, PostgreSQL: first 6 of 8 rows
| name | age_months |
|---|---|
| Pickles | 84 |
| Luna | 60 |
| Bruno | 108 |
| Ziggy | 72 |
| Tofu | 132 |
| Socks | 96 |
The fix returns, SQLite: first 6 of 8 rows
| name | age_months |
|---|---|
| Pickles | 84 |
| Luna | 60 |
| Bruno | 108 |
| Ziggy | 72 |
| Tofu | 132 |
| Socks | 96 |
Experiment with it: PostgreSQL playground·SQLite playground
What SQLite does instead
SQLite accepts aliases in WHERE as a non-standard extension, so the same query works there. Don't rely on it: PostgreSQL, SQL Server and Oracle all reject it.
Official documentation
Stop hitting this error
Practise the concept behind it in a five-minute lesson, or read the full guide: SQL WHERE clause: filtering rows.