Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql delete all rows older than 30 days

Tags:

sql

mysql

There are a lot of questions on how to delete all rows older than 30 days but i can't find anything same with mine so i can fix it

i need to delete some records of messages that are older than 30 days, the column name with the date is named sentOn and the rows in that column looks like this 2018-01-12 12:25:00 How should i format my query to delete all records from the table containing those that are older than 30 days?

DELETE FROM messages WHERE sentOn < '2018-02-21 00:00:00';

would this work?

EDIT: above query works but very very slowly any way to make it faster? i tried now() but it gives error that the function is wrong

like image 446
AlexGr Avatar asked Mar 15 '18 22:03

AlexGr


People also ask

How do you bulk delete rows in SQL?

There are a few ways to delete multiple rows in a table. If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

How do I get last 30 days records in SQL?

How do I find last 30 days in SQL? SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

Can we use limit with Delete in SQL?

You cannot use ORDER BY or LIMIT in a multiple-table DELETE . The table_references clause lists the tables involved in the join, as described in Section 13.2. 10.2, “JOIN Clause”. For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted.


1 Answers

The following code will delete the records of messages that are older than 30 days

DELETE FROM messages WHERE sentOn < NOW() - INTERVAL 30 DAY;

The NOW() method in MySQL is used to pick the current date with time. INTERVAL 30 DAY used for subtracting 30 days from the current date. After the above query, you can check the current table using the SELECT statement. Thank you!

like image 96
Vignesh VS Avatar answered Sep 23 '22 22:09

Vignesh VS