21

We use mysql server as a centralized logging system and I want to have a job to delete\clean the table entries that are more than 3 months old regularly. What is the best way to do this?

Thanks in advance.

-hinling

1

4 Answers 4

84

Do you store the date an item is created in a field?

If so,

DELETE FROM myTable WHERE dateEntered < DATE_SUB(NOW(), INTERVAL 3 MONTH);

should work...

You could run it in a scheduled task/cron job...

1
  • 6
    Don't mean to necro your post, but this certainly helped me tons. thank you
    – Eon
    Aug 3, 2011 at 18:37
5

MySQL 5.1 supports Events. I haven't actually used them myself, so I won't vouch for them. However, if all you want to do is to run a DELETE statement on a regular basis, I think that it would work well enough.

1
  • 4
    CREATE EVENT 'prune_table' ON SCHEDULE EVERY 5 MINUTE DO DELETE FROM myTable WHERE timestamp < NOW() - 600;
    – Vincent
    Apr 27, 2016 at 18:21
2

A simple way would be to scheduled a job that runs every night that calls a stored procedure to delete all rows older than three months. Depending on your O/S it should be easy to do. Do it each night and the amount of deleted data won't be as much as doing it once a month or so.

I have also in the past, had code in my SP that inserted data to do the deletes of unneeded data at that time, so basically every time a row is inserted, right after the insert in ran a 'cleanup' proc that did a bit of maintenance. This wouldn't be my first choice, but its doable if the number of inserts is low, and the deletes can be done fast (you don't want to slow the user down). Nice side-effect of this is the data is always clean (i.e. all data is always <= 3 months old), but not sure if that matters in your app.

You should also consider archiving the rows to another table instead in addition to deleting them, if there is any chance you might want the data someday for another purpose. I always do this, and you'd be surprised what a hero you can look like when some manager who doesn't even know you are saving the data, suddenly has an urgent need for it....and you can deliver for them.

1
  • assume you are deleting data for performance reasons, i.e. to keep the db small, does it matter if you move the deleted data to a table or db? Nov 6, 2015 at 0:17
-1

Paraphrasing your question, "I have code that doesn't depend on the client, which I want to run on the database multiple times, and I don't need to see output", then the answer is "write a stored proc, and call it from whatever client on a regular basis".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.