Full answer
Setup for the example:
sql
CREATE TABLE logs (id bigint PRIMARY KEY, created date);
INSERT INTO logs SELECT g, date '2026-01-01' + (g % 330) FROM generate_series(1, 30000) g;
CREATE PROCEDURE purge_logs(before date, batch int)
LANGUAGE plpgsql AS $$
DECLARE
removed int;
total int := 0;
rounds int := 0;
BEGIN
LOOP
DELETE FROM logs WHERE id IN (SELECT id FROM logs WHERE created < before ORDER BY id LIMIT batch);
GET DIAGNOSTICS removed = ROW_COUNT;
EXIT WHEN removed = 0;
total := total + removed;
rounds := rounds + 1;
COMMIT;
END LOOP;
RAISE NOTICE 'removed % rows in % batches', total, rounds;
END;
$$;sql
CALL purge_logs('2026-04-01', 2500);Output:
text
NOTICE: removed 8189 rows in 4 batches
CALLsql
SELECT min(created) AS oldest, count(*) AS remaining FROM logs;PostgreSQL returns:
text
oldest | remaining
------------+-----------
2026-04-01 | 21811
(1 row)The procedure removes rows older than April in batches of 2,500, committing after each batch, which a function cannot do; the notice reports the total and the number of batches. Each batch selects ids through the primary key, so it stays cheap as the table shrinks; with an index on created, the subquery would also avoid scanning. In production, add a short pg_sleep between batches to let replicas and autovacuum keep up, run outside peak hours, and log progress. CALL must not be wrapped in an explicit transaction block, or the COMMITs inside fail.
sql
CREATE TABLE logs (id bigint PRIMARY KEY, created date);
INSERT INTO logs SELECT g, date '2026-01-01' + (g % 330) FROM generate_series(1, 30000) g;
CREATE PROCEDURE purge_logs(before date, batch int)
LANGUAGE plpgsql AS $$
DECLARE
removed int;
total int := 0;
rounds int := 0;
BEGIN
LOOP
DELETE FROM logs WHERE id IN (SELECT id FROM logs WHERE created < before ORDER BY id LIMIT batch);
GET DIAGNOSTICS removed = ROW_COUNT;
EXIT WHEN removed = 0;
total := total + removed;
rounds := rounds + 1;
COMMIT;
END LOOP;
RAISE NOTICE 'removed % rows in % batches', total, rounds;
END;
$$;
CALL purge_logs('2026-04-01', 2500);
SELECT min(created) AS oldest, count(*) AS remaining FROM logs;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Large single deletes cause long locks and WAL bursts
- Batch with COMMIT between rounds
- Procedures can commit, functions cannot
- Pause between batches for replicas
- Partition dropping is better still
Common mistakes
- Deleting 100 million rows in one statement
- Calling the procedure inside BEGIN ... COMMIT
Follow-ups
- How would you resume after an interruption?
- How do batch sizes affect lock and WAL behaviour?
Tips
- Show the notice