How-To Guide

How to Implement Efficient Bulk Deletes

Delete large volumes of rows efficiently: batch the deletes, control vacuum and bloat, prefer partition or table drops, and avoid long locks.

On this page

  1. Introduction
  2. Estimate before you delete
  3. Batch the deletion
  4. Watch bloat and vacuum
  5. Prefer partition drops for ranges
  6. Test with realistic volume
  7. Common pitfalls
  8. Conclusion

Introduction

Deleting a large number of rows is a maintenance operation that is easy to write and easy to get wrong. A single DELETE that removes millions of rows holds locks for the entire duration, inflates the transaction log, blocks writers, and leaves the table bloated. Done well, the same retention or cleanup is short, non-blocking, and leaves the table healthy. The difference is batching and, where the data shape allows, dropping structure instead of deleting rows.

This tutorial covers how to estimate the volume, how to batch a delete so each transaction is short, how to manage the bloat and vacuum that follow, and when to prefer detaching a partition or swapping tables over a row-by-row delete. The examples use PostgreSQL, but the batching logic and the bloat concern apply to any MVCC database.

Estimate before you delete

Count the rows first, both to size the work and to choose the method. A few thousand rows can be deleted in one statement. Hundreds of thousands or millions need batching, and a whole time range is usually better handled by dropping a partition. The count also tells you how much transaction log the delete will generate, which matters if the database is near a capacity limit.

Decide whether the delete can be replaced by structure. If the rows to remove form a contiguous range, such as everything older than a date, partition the table if it is not already partitioned, then detach and drop the range. This is dramatically faster and leaves no bloat, because it removes files rather than marking rows dead. Reach for this whenever the retention shape is a range.

-- size the work before choosing a strategy
SELECT count(*) AS to_delete
FROM events
WHERE created_at < now() - interval '90 days';

Batch the deletion

When the delete cannot be replaced by structure, do it in chunks. Select a bounded set of ids or use a WHERE with a primary-key range, delete up to a limit, commit, and repeat until no rows remain. Each committed chunk releases its locks, letting writers proceed and letting vacuum reclaim space between chunks. Choose a chunk size that keeps each transaction short without making the loop impractically long.

Delete by an indexed predicate so each chunk finds its rows quickly; an unindexed predicate makes every chunk a sequential scan, turning a batched delete into repeated full scans. If the predicate is on a timestamp, index it, or use the partition key. Loop with a guard so a query that matches nothing cannot spin forever, and sleep briefly between chunks to avoid saturating the database.

-- delete in bounded chunks, committing each one
DELETE FROM sessions
WHERE id IN (
  SELECT id FROM sessions
  WHERE last_seen < now() - interval '30 days'
  ORDER BY id
  LIMIT 5000
);

Watch bloat and vacuum

Every DELETE leaves dead tuples that vacuum must reclaim. On a large delete, autovacuum may not keep up, and the table and its indexes bloat, making subsequent reads scan more pages. Monitor the dead tuple count and the table size, and be prepared to run VACUUM manually or adjust autovacuum thresholds for this table. Index bloat is often worse than table bloat, so check index sizes too.

After a very large delete, a VACUUM (not FULL) returns dead space for reuse inside the table without taking an exclusive lock. VACUUM FULL rewrites the table and returns space to the operating system, but it takes an exclusive lock and needs free disk for the rewrite; use it only when you must shrink the file and can tolerate the lock. Reserve VACUUM FULL for scheduled maintenance windows.

SELECT relname, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'sessions'
ORDER BY n_dead_tup DESC;

Prefer partition drops for ranges

When retention removes whole time ranges, detaching and dropping a partition does the same work in constant time. Detach changes metadata, and drop removes the files. No row-by-row work, no large transaction log, no bloat. This is the single strongest argument for partitioning a time-series table, and it turns a multi-hour cleanup into seconds.

A table swap achieves a similar effect without partitioning: create a new table, copy the rows to keep, then swap the names and drop the old table. This is useful when the keep-set is a small subset of a slightly structured table, but it needs exclusive access during the swap and enough disk for the new table. Weigh it against the simpler batched delete based on how selective the keep-set is.

ALTER TABLE sessions DETACH PARTITION sessions_2025_10 CONCURRENTLY;
DROP TABLE sessions_2025_10;  -- constant-time removal of the whole range

Test with realistic volume

Run the delete against a dataset of realistic size and assert it completes within the time budget without blocking writers. Measure the lock wait of a concurrent write during the delete to prove the batching kept locks short. Assert the row count afterward matches the count that should remain, so an off-by-one in the chunk boundary does not silently leave rows or delete too many.

# drive batched deletes while a writer runs, and assert the writer is not blocked for long
( while true; do psql -d app -c "INSERT INTO sessions(last_seen) VALUES (now())" >/dev/null; done ) &
node scripts/batch-delete.mjs
# assert max lock wait observed is small and the final count equals the expected keep-set

Common pitfalls

Deleting millions of rows in one statement, batching without an index on the predicate so each chunk scans the table, ignoring bloat after the delete, using VACUUM FULL outside a maintenance window, and not testing with realistic volume are the recurring mistakes. Batching by an indexed predicate, monitoring dead tuples, preferring partition drops for ranges, and testing at scale address them.

Conclusion

A bulk delete is a maintenance operation, not a query. Estimate the volume, replace range removals with a partition drop where possible, batch the rest by an indexed predicate with short transactions, watch bloat and vacuum, and test at realistic scale. Self-check by proving a concurrent writer is not blocked for long and that the final row count matches the keep-set. Done deliberately, cleanup stays cheap instead of becoming a lock-heavy event.

Sources: PostgreSQL: VACUUM and dead tuples, PostgreSQL: DELETE statement, PostgreSQL: Deletes and partitioning for retention.

FAQ

Why not delete millions of rows in one statement?
A single large DELETE holds locks for the whole duration, writes a huge transaction log, and can block writers and vacuum. Batching keeps each transaction short so concurrency and maintenance continue between chunks.
Does DELETE reclaim disk space?
Not immediately. DELETE marks rows as dead; the space is reused by later inserts and reclaimed by vacuum. To return space to the operating system, or to remove a whole time range, detaching and dropping a partition or swapping tables is faster and leaves no bloat.

Related Examples