2

So I want to purge some data from the system which is older then 2 years.

I have a datetime field where I store.

I know I can do something like

SELECT * FROM `table` where date_field < (??? what goes here)

My problem is i think how do I calculate the date, or maybe I am confused

Uffo
  • 9,628
  • 24
  • 90
  • 154
  • https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add may help you. `DATE_ADD(date,INTERVAL expr unit)`, `DATE_SUB(date,INTERVAL expr unit`) along with `now()`. also: http://stackoverflow.com/questions/3887509/mysqls-now-1-day – xQbert Mar 25 '16 at 15:25
  • Wouldn't you need to use > now-2 years? instead of < though? – xQbert Mar 25 '16 at 15:28

5 Answers5

5

For a specific answer in case the Manual isn't clear enough:

SELECT * FROM `table` where date_field < (now() - interval 2 year)
xQbert
  • 34,733
  • 2
  • 41
  • 62
4

Use DATE_SUB

SELECT * FROM `table` 
where date_field < DATE_SUB(CURDATE(), INTERVAL 2 YEAR)
baao
  • 71,625
  • 17
  • 143
  • 203
3

may this can help :

SELECT EXTRACT(YEAR FROM `date`) AS year 
from table 
having year< (EXTRACT(YEAR from CURDATE())-2)
HichamEch
  • 635
  • 1
  • 10
  • 18
2

You can use INTERVAL:

SELECT * FROM `table` WHERE date_field < DATE_SUB(CURDATE(),INTERVAL 2 YEAR);

Referenced from https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.

Panda
  • 6,955
  • 6
  • 40
  • 55
1

SELECT * FROM table where date_field < DATE_SUB(NOW(),INTERVAL 2 YEAR);

Tilak Raj
  • 472
  • 4
  • 12