I would like to know if is possible to create a stored procedure that automatically, every day at 00:00, deletes every row of every table that is over 7 days.
I have seen few solutions but not sure if its what I am looking for, and would be nice if someone has any good example. I know this could be done with simple scripts in python and php, but I would like something more automated by MySQL.
Any help would be really appreciate.
Thanks!
You can use below stored procedure and either schedule it by crontab or through events.
Note: Just change mydb with your Database, which database tables data you want to delete and test first in testing environment.
Mysql has its EVENT functionality for avoiding complicated cron interactions when much of what you are scheduling is sql related, and less file related. See the Manual page here. Hopefully the below reads as a quick overview of the important steps and things to consider, and verifiable testing too.
ooops, the event scheduler is not turned on. Nothing will trigger.
SET GLOBAL event_scheduler = ON; -- turn her on and confirm below
Schema for testing
Create 2 events, 1st runs daily, 2nd runs every 10 minutes
Ignore what they are actually doing (playing against one another). The point is on
time difference
approaches and scheduling....
Show event statuses (different approaches)
Random stuff to consider
drop event someEventName;
-- <----- a good thing to know aboutcan't alias datediff and use in where clause in 1 line, so
get more exact, 168 hours for 1 week old
The link to the Manual Page shows quite a bit of flexibilty with interval choices, shown below:
Concurrency
Embed any concurrency measures necessary that multiple events (or multiple firings of the same event) don't cause data to run amok.
Set and Forget
Remember, for now, because you are going to forget it, that these events just keep firing. So build in solid code that will just keep running, even when you forget. Which you most likely will.
Your particular requirements
You need to determine which rows need to be deleted first by table, such that it honors Primary Key constraints. Just lump them all in proper order inside of the obvious area via the CREATE EVENT statement, which can be massive.