Output columns are visible in the ORDER BY
or GROUP BY
clause, because those are applied after evaluating expressions in the SELECT
clause. They are not visible in the WHERE
or HAVING
clause. So you cannot reference the output column name year
. You would have to repeat the expression based on input columns. Obviously, there is an input column of the same name, or you would get an exception. Details:
For your query to be fast, you should rather use a sargable predicate:
SELECT EXTRACT(YEAR FROM pub_date) AS year
FROM news_stories
WHERE pub_date >= '2010-1-1'::date;
This is generally faster, because Postgres can compare values in the pub_date
to the given value directly, without extracting the year from every row first.
More importantly, a plain index on pub_date
can be used this way - if Postgres expects that route to be faster (index-only scan or selective enough).