0

I have a table like this in postgresql:

Name DOB
ABC '2011-03-03'
XYZ '2009-01-01'

What is the query that I should use to get the output data in the below format(only year instead of date) also I want to retrieve data that is greater than 2010 only:

Name DOB
ABC '2011'
1

1 Answer 1

2

Format DOB using to_char.

select "Name", to_char(DOB, 'yyyy') DOB 
from the_table
where extract('year' from DOB) > 2010;

If DOB is character rather than date type then it has to be first cast to date:

select "Name", to_char(DOB::date, 'yyyy') DOB 
from the_table
where extract('year' from DOB::date) > 2010;

If your date represented as text has "month/day/year" format then use to_date to convert it to date.

select "Name", to_char(to_date(DOB, 'mm/dd/yyyy'), 'yyyy') DOB 
from the_table
where extract('year' from to_date(DOB, 'mm/dd/yyyy')) > 2010;

Unrelated but do not store dates as formatted text. You have data type date for this.

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting this error: (psycopg2.errors.DatetimeFieldOverflow) date/time field value out of range: "06/27/2022" HINT: Perhaps you need a different "datestyle" setting. the date was of type string, so I used the query, select Name,to_char(date::date, 'yyyy') date from <tablename> (Column name is date and not DOB will this create any issue)
Put column name in double quotes, i.e. "date" and it will not be an issue. However using reserved words for column names is not a good idea at all. I have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.