Satish K Satish K - 26 days ago 6
SQL Question

How to get only year from age() function in postgresql select query

select age(cast(dob as date))
from mas_patient_details


when i run above query it returns

age
----------
39 years 5 mons 19 days
13 years 2 days
69 years 2 days
41 years 11 mons 25 days


select age(cast(dob as date)) from mas_patient_details where age <= 59

it returns

39 years 5 mons 19 days
13 years 2 days
69 years 2 days
41 years 11 mons 25 days


how correct my query?

Answer

If column fu is of data type DATE, you could use

SELECT EXTRACT(YEAR FROM fu) FROM mydate;

and if it is varchar, you convert it to date using to_date()

SELECT EXTRACT(YEAR FROM to_date(fu, <your pattern>)) FROM mydate;

In your case:

select EXTRACT(YEAR FROM age(cast(dob as date))) from mas_patient_details where age <= 59;
Comments