// SQL snippet

Archive old rows to a history table

Hot tables slow down as they grow, but old rows still belong somewhere. Move them to a history table in one statement: no window where rows are in both or neither.

Main statement
PostgreSQL
Também cobre
SQL Server MySQL

The task

The events table carries years of expired rows that slow every scan, yet deleting them outright would lose data the business still occasionally needs.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
WITH moved AS (
    DELETE FROM events
    WHERE occurred_at < now() - interval '2 years'
    RETURNING *
)
INSERT INTO events_history
SELECT * FROM moved;

Como funciona

The CTE deletes exactly the rows it returns, and the outer INSERT writes them to the archive in the same statement, so either both happen or neither does; a crash never leaves a row in both tables or in neither. SELECT * relies on the two tables having the same columns in the same order, so list the columns explicitly once the history table can drift. Moving millions of rows at once holds row locks on all of them and leaves that many dead tuples for vacuum, so batch it as in the next variant.

Variations

PostgreSQL: batched

PostgreSQL
-- repeat until 0 rows moved; each pass stays small
WITH moved AS (
    DELETE FROM events
    WHERE id IN (
        SELECT id FROM events
        WHERE occurred_at < now() - interval '2 years'
        LIMIT 10000)
    RETURNING *
)
INSERT INTO events_history SELECT * FROM moved;

SQL Server

SQL Server
-- the OUTPUT target cannot have enabled triggers or take
-- part in a foreign key; add TOP (10000) to batch
DELETE FROM dbo.Events
OUTPUT deleted.* INTO dbo.Events_History
WHERE occurred_at < DATEADD(year, -2, SYSUTCDATETIME());

MySQL

MySQL
-- no DELETE ... RETURNING; copy, then delete the same rows.
-- Fix the cutoff once: NOW() changes between statements.
SET @cutoff := NOW() - INTERVAL 2 YEAR;
START TRANSACTION;
INSERT INTO events_history
    SELECT * FROM events
    WHERE occurred_at < @cutoff;
DELETE FROM events
    WHERE occurred_at < @cutoff;
COMMIT;

Questions that come up

How often should I run the archive job?

Often enough that each run moves a bounded number of rows. A nightly job that moves one day's worth keeps locks short and gives vacuum or the transaction log a steady small load, while a quarterly purge of 50 million rows does neither. If retention is a fixed window, partition the table by date and drop or detach old partitions instead (see rotate-partition).

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.