0

In the query below, the parameter date_part('year', CURRENT_DATE) - f.birth_year is repeated three times. How can I replace it by its alias age ?

SELECT
    date_part('year', CURRENT_DATE) - f.birth_year AS age
FROM
    public.foo f
WHERE
    date_part('year', CURRENT_DATE) - f.birth_year >=20 AND
    date_part('year', CURRENT_DATE) - f.birth_year <=30
DevonDahon
  • 7,460
  • 6
  • 69
  • 114

2 Answers2

1

You can't reuse a select alias in the where clause. You need to repeat the expression, or use a subquery or cte.

For what it's worth, you can use between to have the expression just once instead of twice in the where clause:

SELECT date_part('year', CURRENT_DATE) - f.birth_year AS age
FROM public.foo f
WHERE date_part('year', CURRENT_DATE) - f.birth_year BETWEEN 20 AND 30

As for the subquery solution, that would be:

SELECT *
FROM (
    SELECT date_part('year', CURRENT_DATE) - f.birth_year AS age
    FROM public.foo
) f
WHERE age BETWEEN 20 AND 30
GMB
  • 216,147
  • 25
  • 84
  • 135
0

A CTE lets you name expressions so you can avoid repeating them. By the way, that's not the correct calculation for age:

with data as (
    SELECT date_part('year', CURRENT_DATE) - birth_year AS age
    FROM public.foo
)
select * from data
WHERE age >= 20 AND <= 30;
shawnt00
  • 16,443
  • 3
  • 17
  • 22