Efficiently Deleting Old MySQL Rows with Rolling Truncation
In many applications, there's a need for periodic removal of rows older than a specified age. When handling high-traffic tables, finding an efficient method for this is crucial.
Current Approach
Previously, tables were truncated in one large batch using a cron job running hourly. While this prevented application hangs, it introduced scalability limitations during periods of heavy write traffic.
Alternative: Scheduled Events
An alternative to the current method is to utilize MySQL's Event feature. Events allow automated execution of database tasks on a scheduled basis.
Example Event for Rolling Truncation
Here's a sample event that will delete rows in the ' tableName ' table that are older than 30 days:
SET @@GLOBAL.event_scheduler = ON; CREATE EVENT AutoDeleteOldNotifications ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY ON COMPLETION PRESERVE DO DELETE LOW_PRIORITY FROM databaseName.tableName WHERE datetime < DATE_SUB(NOW(), INTERVAL 30 DAY);
Benefits of Using Events
Events provide several advantages:
The above is the detailed content of How Can MySQL Events Improve Efficiency and Scalability for Deleting Old Rows?. For more information, please follow other related articles on the PHP Chinese website!