Home > Database > Mysql Tutorial > How Can I Automate Daily Row Deletion in MySQL Based on Age?

How Can I Automate Daily Row Deletion in MySQL Based on Age?

Linda Hamilton
Release: 2024-12-06 06:00:18
Original
856 people have browsed it

How Can I Automate Daily Row Deletion in MySQL Based on Age?

Automating Row Deletion in MySQL with Stored Procedures

You aim to create a MySQL stored procedure that removes rows older than seven days from all tables at midnight daily. While scripting solutions exist, this article focuses on a more automated approach using MySQL's EVENT functionality.

Creating the Procedure

First, ensure the event scheduler is enabled:

SET GLOBAL event_scheduler = ON;
Copy after login

Then, create an event that triggers daily at 00:00:

CREATE EVENT `delete7DayOldRows`
ON SCHEDULE EVERY 1 DAY STARTS '2023-03-01 00:00:00'
ON COMPLETION PRESERVE
DO
  -- Your delete logic here
END;
Copy after login

Defining the Deletion Logic

Inside the DO block of the event, specify the deletion logic. Here's an example:

BEGIN
  DECLARE tableName VARCHAR(255);
  DECLARE cursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = 'your_database_name';
  OPEN cursor;
  FETCH cursor INTO tableName;
  WHILE tableName IS NOT NULL DO
    DELETE FROM `your_database_name`.`tableName` WHERE CURDATE() - INTERVAL 7 DAY > updateDt;
    FETCH cursor INTO tableName;
  END WHILE;
  CLOSE cursor;
END;
Copy after login

This logic iterates through all tables in the specified database and deletes rows where the updateDt column is more than seven days old.

Considerations

  • Concurrency: Implement mechanisms to prevent data integrity issues if multiple events execute concurrently.
  • Testing: Thoroughly test the procedure to ensure it operates as intended.
  • Error Handling: Consider adding error handling within the procedure to catch and address any errors.
  • Identification: Keep track of the scheduled events to easily identify and manage them.

The above is the detailed content of How Can I Automate Daily Row Deletion in MySQL Based on Age?. 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