Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a MySQL record after a certain time

Tags:

I want to delete some messages from my MySQL database after 7 days.

My message table rows have this format: id | message | date

The date is a timestamp in the normal format; 2012-12-29 17:14:53

I was thinking that an MySQL event would be the way to go instead of a cron job.

I have what I guess is a simple question to an experienced SQL person, how do I code the delete messages portion in brackets below?

An example would be appreciated, Thanks.

 DELIMITER $$
   CREATE EVENT delete_event
   ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
   ON COMPLETION PRESERVE
  DO
    BEGIN
      DELETE messages WHERE date >= (the current date - 7 days);
    END;
$$;
like image 739
Mike Avatar asked Dec 31 '12 01:12

Mike


People also ask

How do I delete a specific date in SQL?

delete from YOUR_TABLE where your_date_column < '2009-01-01'; This will delete rows from YOUR_TABLE where the date in your_date_column is older than January 1st, 2009. i.e. a date with 2008-12-31 would be deleted.

Is deletion possible in MySQL?

The Delete query in MySQL can delete more than one row from a table in a single query. This proves to be advantages when removing large numbers of rows from a database table. Once a Delete row in MySQL row has been deleted, it cannot be recovered.

How do I delete multiple records in MySQL?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.


1 Answers

You can try using this condition:

WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)

So that the whole SQL script looks like this:

CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE

DO BEGIN
      DELETE messages WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY);
END;

However, on your place I would solve the given problem with a simple cron script. The reasons to do this is simple: it's easier to maintain the code, no ugly SQL workarounds, integrates smoothly with your system.

like image 180
Jordan Jambazov Avatar answered Sep 27 '22 19:09

Jordan Jambazov