How to Delete Millions of Rows in MySQL in Batches

Delete millions of rows in MySQL without long locks or replica lag: batch DELETE with LIMIT, pt-archiver --purge, partition drops and copy-and-swap.

  • Go to the profile of Safoor Safdar
·9 min read

You need to purge 60 million old rows from a busy MySQL table, and a single DELETE would lock it for hours. Replicas fall behind, the undo tablespace grows, and a failure halfway through rolls the whole thing back. You can get the same result in small, safe steps.

Key Takeaways

  • Delete in batches of about 1,000 rows with DELETE ... WHERE ... LIMIT, commit each batch, and pause between batches.
  • Put an index on the column in your WHERE clause, or InnoDB locks every row the scan touches.
  • pt-archiver --purge runs the batch loop for you, with progress output, sleeps and replica lag checks.
  • Run pt-archiver with --dry-run first to print the queries it plans to execute.
  • To remove most of a table, copy the rows you keep into a new table and swap it in, or drop a partition.

The cost of one huge DELETE

A single DELETE of millions of rows runs as one transaction, so every cost lands at once. You pay in locks, undo log and replication.

Batch deleting is the practice of removing rows in small committed chunks, so each transaction holds locks and undo records for a short time.

The old way looks like this:

DELETE FROM quote WHERE created_at < '2022-07-01';

The MySQL InnoDB locking docs say DELETE FROM ... WHERE ... sets an exclusive next-key lock on every record the search encounters. InnoDB releases those locks at commit. One giant transaction keeps them for its whole run and blocks inserts into the locked gaps.

Without a suitable index, the same page says MySQL scans the entire table and every row becomes locked. The DELETE reference adds that a large delete can exceed the InnoDB lock table size.

Undo log is the second cost. InnoDB marks each deleted row and writes an undo record so it can roll back. The multi-versioning docs warn that uncommitted work stops InnoDB from discarding undo data, and the rollback segment can fill its undo tablespace. If the statement fails at row 50 million, InnoDB undoes all 50 million.

Replication is the third. The binary log docs state that MySQL writes the entire transaction to the binary log at commit. Replicas see nothing until the source finishes, and then they start replaying the whole delete. Replica lag climbs while they work through it.

The batch delete pattern in plain SQL

Delete a fixed number of rows per statement, commit, sleep, and repeat until a batch removes zero rows. The DELETE reference describes the same loop: repeat the statement until the affected row count is less than the LIMIT.

Start with an index on the column you filter by:

CREATE INDEX idx_quote_created_at ON quote (created_at);

Count the rows first, so you can check the result afterward:

SELECT COUNT(*) FROM quote WHERE created_at < '2022-07-01';

Write the condition as a plain range on the column. The original version of this post used DATE(updated_at) < '2022-07-01'. Wrapping the column in a function stops MySQL from using a plain index on it, so each batch scans more rows.

Then run the loop. This stored procedure deletes 1,000 rows per statement and sleeps half a second between batches:

DELIMITER //

CREATE PROCEDURE purge_old_quotes()
BEGIN
  DECLARE rows_deleted INT DEFAULT 1;

  WHILE rows_deleted > 0 DO
    DELETE FROM quote
    WHERE created_at < '2022-07-01'
    ORDER BY created_at, id
    LIMIT 1000;

    SET rows_deleted = ROW_COUNT();
    DO SLEEP(0.5);
  END WHILE;
END //

DELIMITER ;

CALL purge_old_quotes();

With autocommit on, each DELETE commits on its own, so locks and undo records stay small. You don’t change the LIMIT between runs. Each statement deletes the next 1,000 matching rows, because the previous batch removed the earlier ones.

The ORDER BY matters if your binary log uses STATEMENT format. The replication docs call DELETE ... LIMIT unsafe for statement-based replication unless it also has an ORDER BY.

Pick the batch size by time, then by row count. Rick James’s guide to big deletes suggests about 1,000 rows per chunk, and tuning so each DELETE takes under a second. Lower the batch size or raise the sleep if replica lag grows.

Purge rows with pt-archiver

pt-archiver is a Percona Toolkit command that archives or deletes MySQL rows in small batches. With --purge, it deletes matching rows and keeps no copy. It walks an index forward, remembers the last row it fetched, and continues from there.

The pt-archiver docs cover every option. Percona Toolkit is free software under the GPL.

Run the command with --dry-run first. The tool prints the queries it would run and exits without touching data.

pt-archiver \
  --source h=db.example.com,D=shop,t=quote \
  --where "created_at < NOW() - INTERVAL 90 DAY" \
  --purge --limit 1000 --commit-each \
  --dry-run

Read the SELECT and DELETE statements it prints. Check the index and the WHERE clause before you run it for real.

Then drop --dry-run and add progress, sleep and bulk delete options:

pt-archiver \
  --source h=db.example.com,D=shop,t=quote \
  --where "created_at < NOW() - INTERVAL 90 DAY" \
  --purge --limit 1000 --commit-each \
  --bulk-delete \
  --progress 10000 \
  --sleep 1 \
  --statistics --why-quit
FlagWhat it does
--source h=...,D=...,t=...Connects to host h, database D and table t. Add i= to name the index; otherwise the tool picks one and prefers the primary key.
--where "..."Selects the rows to purge. The tool requires it. Use --where 1=1 to match every row.
--purgeDeletes rows instead of archiving them, so you don’t need --file or --dest.
--limit 1000Fetches and processes 1,000 rows per statement. The default is 1.
--commit-eachCommits once per fetched batch and disables --txn-size.
--bulk-deleteDeletes each batch with one statement instead of one per row. It implies --commit-each.
--progress 10000Prints progress every 10,000 rows.
--sleep 1Sleeps one second between fetches. By default the tool doesn’t sleep.
--dry-runPrints the queries and exits without doing anything.
--statisticsPrints timing statistics on exit.
--why-quitPrints the reason the tool stopped, unless it ran out of rows.

The docs add two cautions for --bulk-delete. It may not run faster with a complex WHERE clause. With a plugin that skips some rows, the bulk delete still removes them.

Add --check-replica-lag to pause the purge while a replica falls behind:

  --check-replica-lag h=replica1.example.com --max-lag 1

The tool waits until that replica’s lag drops below --max-lag, which defaults to one second. Older guides use --check-slave-lag, which the docs now mark as deprecated.

The original version of this post used --limit 10000000 and a broken NOT EXISTS subquery with nested single quotes. A 10-million-row batch brings back the problems batching should solve. Keep --limit in the hundreds or low thousands.

Delete most of a table with copy and swap

If you keep a small fraction of the rows, copy those rows to a new table and swap it in. The DELETE reference recommends this pattern for large InnoDB tables, and it avoids DELETE altogether.

CREATE TABLE quote_new LIKE quote;

INSERT INTO quote_new
SELECT * FROM quote
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);

RENAME TABLE quote TO quote_old, quote_new TO quote;

DROP TABLE quote_old;

The MySQL docs state that no other session can access the tables while RENAME TABLE runs, so the swap is atomic. Rows written between the copy and the rename stay in quote_old. Copy them across before you drop it, or stop writes for the swap window.

Watch for three traps. CREATE TABLE ... LIKE doesn’t copy foreign key definitions, per the CREATE TABLE LIKE docs. You need disk space for both tables during the copy. Drop quote_old outside peak hours.

An earlier version of this post renamed the empty table in first and copied the 30 days back afterward. New inserts then started from an empty table, and their auto-increment IDs could collide with the rows you copy back. The MySQL order above avoids that.

Drop a partition for recurring purges

If you purge by date every month, partition the table by that date. Dropping a partition removes its rows without a row-by-row DELETE.

ALTER TABLE quote DROP PARTITION p2022_06;

The partition management docs warn that dropping a partition deletes all data stored in it. The server also doesn’t report a row count the way DELETE does. Converting an existing large table to partitions takes an ALTER TABLE on the whole table, so plan it for a quiet window.

For moving large MySQL datasets between servers instead of deleting them, see my notes on exporting and importing large MySQL data. If you run Aurora MySQL, watch IOPS on a CloudWatch dashboard while a purge runs.

What I chose in production

I’ve used pt-archiver to delete millions of rows of outdated data, with the --sleep and replica-lag checks above. It takes longer than one big DELETE, but it keeps resource use low and doesn’t interrupt the live service.

A purge during business hours competes with user queries. Watch your p99 latency while the first batches run, and raise --sleep if it climbs.

For one cleanup, I tested these approaches against a 40 GB table before touching production. I then chose copy-and-swap over pt-archiver for the production run. Your choice depends on how much of the table you’re deleting and how long the job can run.

Frequently asked questions

How do I delete millions of rows in MySQL?

Delete in batches. Run DELETE ... WHERE ... LIMIT 1000 in a loop on an indexed column, commit each batch and pause between them. Use pt-archiver --purge to automate the loop, or copy and swap the table if you delete most of it.

How does pt-archiver purge work?

pt-archiver --purge fetches matching rows in batches of --limit rows and deletes them without saving a copy. It walks an index forward and commits per batch with --commit-each. Run it with --dry-run first to see the queries.

How do I delete in batches in MySQL?

Add LIMIT to your DELETE and repeat it until it affects zero rows. A stored procedure with a WHILE loop, ROW_COUNT() and DO SLEEP() handles this inside MySQL. Add ORDER BY if you use statement-based replication.

Can I delete from a large MySQL table without locking it?

InnoDB locks the rows each DELETE touches, so you can’t avoid locks. You can keep them short. Index the WHERE column, delete 1,000 rows per commit, and sleep between batches so other queries get through.