Select Page

I ran into a problem recently where I needed to delete all rows in a MySQL table that were older than three months. To delete MySQL/MariaDB rows older than date xxxx-xx-xx, I was able to accomplish this with the following statement:

Substitute table and column, and a proper date option. Note that column does need to have a datetime or timestamp data type for the comparison to work.

The DATE_SUB function subtracts a time period from the date specified. In this statement, NOW grabs the current date from which INTERVAL 3 MONTHS is subtracted (along with the < operand).

Here’s another more complex example (which includes joins and nested select statements) which I wrote when building my Amzbot Slack app. The query was written in PHP (so as to explain the $vars), but it’s another example of how you can perform date/time operations using DATE_SUB. Hopefully you can adapt these examples to fit your needs.

The difference between NOW and CURDATE is this: NOW returns a full timestamp 2016-06-29 23:50:26 whereas CURDATE returns only the date and not time 2016-06-29.

Your available options for the INTERVAL statement can be any from the following table:

unit Value Expected expr Format
MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_MICROSECOND 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_HOUR 'DAYS HOURS'
YEAR_MONTH 'YEARS-MONTHS'

Here’s a third example using BETWEEN to perform date comparison operations.

So did you get it to work? Were you able to write the query that you needed? Let me know how it went for you below in the comments, or if you had any trouble getting it to work.