Skip to content
Advertisement

SQL – How to select date from the past 5 years to include 1st of Jan of the oldest year

I am trying to select data entered for the past 5 years (to start from the 1st of Jan of the first or oldest year). I’ve constructed the query below but it does not begin from the 1st of January of the oldest year.

SELECT col_name FROM table_name WHERE entry_date > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 5 year

Any help would be appreciated.

Advertisement

Answer

You seem to be using MySQL. The simplest method is going to be:

SELECT col_name
FROM table_name
WHERE YEAR(entry_date) >= YEAR(curdate()) - 5;

Note that the use of YEAR() is not index-friendly. However, selecting five years worth of data is probably not going to benefit from an index anyway.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement