Using column alias in a WHERE clause doesn't work
The manual clarifies here:
An output column's name can be used to refer to the column's value in
ORDER BY
andGROUP BY
clauses, but not in theWHERE
orHAVING
clauses; there you must write out the expression instead.
That's according to the SQL standard and may not be very intuitive. The (historic) reason behind this is the sequence of events in a SELECT
query. WHERE
and HAVING
are resolved before column aliases are considered, while GROUP BY
and ORDER BY
happen later, after column aliases have been applied.
Also note that conflicts between input and output names are resolved differently in ORDER BY
and GROUP BY
- another historic oddity (with a reason behind it, but potentially confusing nonetheless). See:
- PostgreSQL: How to return rows with respect to a found row (relative results)?
Best to avoid column aliases that conflict with input column names a priori.
Aside: the subquery in your example is just noise since the WHERE
clause is part of the outer query, so the example can be simplified to:
select id, email as electronic_mail
from users t
where electronic_mail = ''; -- doesn't work