Work with records older then x days

For the sake of this example, let’s assume that:

  1. we want to work with records older then 60 days
  2. the table name is ‘table’ (how original!)
  3. the table field with dates is called date_field 🙂

DELETE FROM table WHERE date_field < DATE_SUB(CURDATE(),INTERVAL 60 DAY)

This MySQL command deletes all table rows whose date is older then 60 days from current date – CURDATE() -.


SELECT something FROM table WHERE date_field< DATE_SUB(CURDATE(),INTERVAL 60 DAY)

This MySQL command selects all table rows whose date is older then 60 days from current date – CURDATE() -.


Explanation:

DATE_SUB(date,INTERVAL expr unit) -> Subtracts two dates

CURDATE() -> Returns the current date

unit can be:

  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Be the first to comment

Leave a Reply

Your email address will not be published.


*