Skip to content

Instantly share code, notes, and snippets.

@digitalhitler
Last active September 4, 2018 04:03
Show Gist options
  • Save digitalhitler/80986fa50f3b69c0092dbbfbf581495a to your computer and use it in GitHub Desktop.
Save digitalhitler/80986fa50f3b69c0092dbbfbf581495a to your computer and use it in GitHub Desktop.
Archive old MySQL rows to another table
CREATE DEFINER=`grs`@`localhost` PROCEDURE `ads_archive_updater`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Ads archive updater'
BEGIN
START TRANSACTION;
SELECT COUNT(*) FROM Ads INTO @adsTotal;
SELECT COUNT(*) AS `totalBefore` FROM AdsArchive INTO @archiveBefore;
SELECT `ID` FROM Ads ORDER BY `ID` DESC LIMIT 1000000, 1 INTO @minimalAdId;
INSERT IGNORE INTO AdsArchive SELECT * FROM Ads WHERE `ID` < @minimalAdId LIMIT 500000;
SELECT FOUND_ROWS() INTO @archivedRows;
SELECT COUNT(*) AS `totalAfter` FROM AdsArchive INTO @archiveAfter;
DELETE FROM Ads WHERE `ID` < @minimalAdId LIMIT 500000;
SELECT ROW_COUNT() INTO @deletedRows;
SELECT @adsTotal AS `adsTotal`,
@archiveBefore AS `archiveBefore`,
@archiveAfter AS `archiveAfter`,
@minimalAdId AS `minimalAdId`,
@archivedRows AS `archivedRows`,
@deletedRows AS `deletedRows`;
COMMIT;
# ROLLBACK;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment