简体   繁体   中英

Delete old records from table and backup those records in new backup table before date

I have a MYSQL table that needs to backup old records before 01 Jan 2021, to the new backup table. And delete old records before 01 Jan 2021 from the original table. The original table has a created_on column to filter the date. How can I do this operation?

Probably the quicker way is to do this:

  1. Create a new table:
CREATE TABLE new_table LIKE original_table;
  1. Insert data from 01 Jan 2021 into new table. Depending on the data, this might be much quicker than inserting old data into new table. Simply because if the old data is from year 2001, just imagine how many rows it has compared to a half year of 2021 data:
INSERT INTO new_table SELECT * FROM original_table WHERE created_on >= '2021-01-01';
  1. Rename old and new tables:
RENAME TABLE original_table TO old_table1;
RENAME TABLE new_table TO original_table;
  1. Check if all year 2021 data exists in the new table. Once confirmed, you can proceed to delete 2021 data from the old table OR remain it there; that's up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM