How to delete rows older than 14 days in MySQL?


To delete, use MySQL DELETE. However, to get records older than 14 days, subtract the current date with date interval of 14 days. The syntax for the same is shown below −

delete from yourTableName
where yourColumnName< (curdate() - interval 14 day);

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   DueDate date
);
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(DueDate) values('2019-08-20');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(DueDate) values('2019-08-19');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(DueDate) values('2018-08-19');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(DueDate) values('2018-08-18');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(DueDate) values('2019-08-15');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable ;

This will produce the following output −

+----+------------+
| Id | DueDate    |
+----+------------+
|  1 | 2019-08-20 |
|  2 | 2019-08-19 |
|  3 | 2018-08-19 |
|  4 | 2018-08-18 |
|  5 | 2019-08-15 |
+----+------------+
5 rows in set (0.00 sec)

Following is the query to delete rows older than 14 days −

mysql> delete from DemoTable
   where DueDate − (curdate() - interval 14 day);
Query OK, 4 rows affected (0.62 sec)

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output. Now, all the rows older than 14 days are deleted −

+----+------------+
| Id | DueDate    | 
+----+------------+
|  1 | 2019-08-20 |
+----+------------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

902 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements