53

I need to see only the current year rows from a table.

Would it be possible filter a timestamp column only by current year parameter, is there some function that can return this value?

SELECT * FROM mytable WHERE "MYDATE" LIKE CURRENT_YEAR
1

3 Answers 3

96

In PostgreSQL you can use this:

SELECT * FROM mytable WHERE date_part('year', mydate) = date_part('year', CURRENT_DATE);

The date_part function is available in all PostgreSQL releases from current down to 7.1 (at least).

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

2 Comments

Note that that query will be pretty slow. A better idea would be to do mydate >= date_trunc('year',current_date) AND mydate < date_trunc('year',current_date + interval '1 year')
Thanks a lot for that hint! Any improvement is very much appreciated. I tried to substantiate what you wrote with some measuring. I ran a test on a table containing about 200K records, some 50 columns overall and having 9 different columns of date or timestamp type. The number of records selected differed from 500 to 30K depending on the column. It took your queries up to 10% longer. The best result was near level. Of course I followed rules of statistical investigation. I guess you tried yourself many times. Someone out there who can come up with her or his own measuring?
20

This is pretty old, but now you can do:

SELECT date_part('year', now()); -> 2020

In the place of now you can pass any timestamp. More on Documentation

Comments

6

I prefer this writing

SELECT EXTRACT(YEAR FROM CURRENT_DATE) AS year;

So your query would be:

SELECT * FROM mytable WHERE "MYDATE" = EXTRACT(YEAR FROM CURRENT_DATE);

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

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.