Home > Database > Mysql Tutorial > body text

How Can MySQL Events Improve Efficiency and Scalability for Deleting Old Rows?

Mary-Kate Olsen
Release: 2024-11-08 21:50:02
Original
205 people have browsed it

How Can MySQL Events Improve Efficiency and Scalability for Deleting Old Rows?

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);
Copy after login

Benefits of Using Events

Events provide several advantages:

  • Automated Execution: Tasks run automatically based on the schedule, eliminating the need for manual intervention.
  • Efficient and Scalable: Events execute in the database background, reducing impact on application performance and traffic.
  • Low Priority: The LOW_PRIORITY flag ensures that delete operations don't interfere with read operations during high load.
  • Persistence: The ON COMPLETION PRESERVE ensures that the event is not removed after execution, ensuring its repeatability.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!