MySQL query to delete all rows older than 30 days?


To delete all rows older than 30 days, you need to use the DELETE with INTERVAL. Use < now() i.e. less than operator to get all the records before the current date.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> UserMessage text,
   -> UserMessageSentDate date
   -> );
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Hi','2019-06-01');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values('Hello','2019-07-02');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Awesome','2019-05-04');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Good','2019-01-10');
Query OK, 1 row affected (0.35 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------------+---------------------+
| UserMessage | UserMessageSentDate |
+-------------+---------------------+
| Hi          | 2019-06-01          |
| Hello       | 2019-07-02          |
| Awesome     | 2019-05-04          |
| Good        | 2019-01-10          |
+-------------+---------------------+
4 rows in set (0.00 sec)

Following is the query to delete all rows older than 30 days −

mysql> delete from DemoTable where UserMessageSentDate < now() - interval 30 DAY;
Query OK, 3 rows affected (0.11 sec)

Let us check table records once again −

mysql> select *from DemoTable;

Output

+-------------+---------------------+
| UserMessage | UserMessageSentDate |
+-------------+---------------------+
| Hello       | 2019-07-02          |
+-------------+---------------------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 16:48:40
Advertisements