Sub topic 14
Indexes, locks, and batching
This chapter assumes you can already write UPDATE ... FROM and DELETE ... USING statements, read a basic EXPLAIN plan, and run statements in psql. It covers what these statements cost on a large table, what they lock, and how to split a big change into safe batches.
Why a join-based change can be slow
PostgreSQL plans the join in an UPDATE ... FROM or DELETE ... USING the way it plans a SELECT. The planner picks a nested loop, hash join, or merge join, and it picks scan types for each table. Most slow bulk changes come from a bad join plan, not from the write itself.
The schema from earlier chapters has these join columns:
products.idis a primary key, so it already has an index.price_updates.product_idhas no index.orders.customer_idis a foreign key, but PostgreSQL does not index foreign key columns automatically.
Add indexes for the join columns that lack one:
CREATE INDEX price_updates_product_id_idx ON price_updates (product_id);
CREATE INDEX orders_customer_id_idx ON orders (customer_id);The orders.customer_id index helps in two ways. It speeds up the join when you delete orders for closed customers. It also speeds up deletes from customers, because PostgreSQL must check that no orders row still references the deleted customer.
An index does not always help. If the statement touches most of the table, a hash join with sequential scans is usually faster than thousands of index lookups, and the planner knows this. Run ANALYZE on a table after you bulk-load it so the planner has current row counts.
Reading the plan without running the change
Plain EXPLAIN shows the plan and does not execute the statement:
EXPLAIN
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;EXPLAIN ANALYZE actually runs the statement, so it really changes rows. Wrap it in a transaction that you roll back:
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;
ROLLBACK;The plan shows the target table as Update on products, with the join beneath it. Compare estimated and actual row counts. A large mismatch usually means stale statistics.
The cost of writing rows
PostgreSQL uses multiversion concurrency control (MVCC). An UPDATE never changes a row in place. It writes a new row version and marks the old one dead. A DELETE only marks the row dead. Dead versions stay in the table until VACUUM removes them.
This has three consequences for bulk changes:
- Updating one million rows temporarily needs room for one million extra row versions. The table grows, which is called bloat.
- If the update changes no indexed column and the new version fits on the same page, PostgreSQL can use a heap-only tuple (HOT) update and skip index writes. If you update an indexed column, every index on the table gets a new entry for every row.
- An update that sets a column to the value it already has still writes a new row version.
The last point gives a cheap optimization. Skip rows that would not change:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
AND p.price IS DISTINCT FROM u.new_price;IS DISTINCT FROM treats NULL as an ordinary value, so the comparison never returns NULL. A plain <> would skip rows where either side is NULL.
What these statements lock
Locks explain most surprises when a bulk change runs on a live database.
| Object | Lock taken by UPDATE/DELETE | Effect on others |
|---|---|---|
| Target table | `ROW EXCLUSIVE` table lock | Does not block `SELECT`, `INSERT`, or other `UPDATE`/`DELETE`. Blocks `ALTER TABLE` and `CREATE INDEX` (non-concurrent). |
| Each changed target row | Row-level lock until commit or rollback | Other writers to that row wait. Readers do not wait. |
| Tables in `FROM` or `USING` | `ACCESS SHARE` table lock only | Their rows are read, not locked. Other sessions can change them while you run. |
The last row matters. Joined rows are not locked. If another session changes customers.status while your DELETE ... USING customers runs, your statement works from the snapshot it took when it started. In the default READ COMMITTED isolation level, the exception is a target row that was blocked by another writer. PostgreSQL re-checks the WHERE clause against the newest version of that target row, but it does not re-run the join against newer versions of the other tables.
If you need the joined rows to stay stable, lock them explicitly in a subquery with FOR SHARE or FOR UPDATE.
Row locks are held until the transaction ends
A large statement locks every row it changes until commit. Any other session that wants one of those rows waits. This is why a long bulk update can stall an application.
Two sessions that change overlapping rows in different orders can deadlock. PostgreSQL detects this and cancels one session with an error. To reduce the risk, process rows in a consistent order, for example by primary key.
Set time limits so a bulk job fails fast instead of waiting forever:
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '5min';
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open';
COMMIT;SET LOCAL lasts only until the end of the current transaction.
Batching large changes
Splitting a change into batches has four benefits:
- Each transaction holds its row locks for a short time.
- A failure loses one batch, not hours of work.
VACUUMcan reclaim dead rows between batches.- Write-ahead log (WAL) volume arrives in smaller bursts, which is easier on replicas.
PostgreSQL has no LIMIT on UPDATE or DELETE. Instead, select a batch of keys in a CTE and join the change to it:
WITH batch AS (
SELECT o.id
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'closed'
ORDER BY o.id
LIMIT 5000
FOR UPDATE OF o
)
DELETE FROM orders AS o
USING batch
WHERE o.id = batch.id;FOR UPDATE OF o locks only the selected orders rows, not the customers rows. ORDER BY o.id gives every batch the same lock order, which avoids deadlocks between concurrent batch jobs.
Run this statement repeatedly until it deletes zero rows. In PostgreSQL 11 and later, a DO block can commit between iterations when it is not run inside an explicit transaction:
DO $$
DECLARE
n integer;
BEGIN
LOOP
WITH batch AS (
SELECT o.id
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'closed'
ORDER BY o.id
LIMIT 5000
FOR UPDATE OF o
)
DELETE FROM orders AS o
USING batch
WHERE o.id = batch.id;
GET DIAGNOSTICS n = ROW_COUNT;
EXIT WHEN n = 0;
COMMIT;
END LOOP;
END
$$;A batched update must make progress or the loop never ends. A delete removes the rows from the next batch's search. An update needs a condition that excludes rows already changed, such as p.price IS DISTINCT FROM u.new_price or o.status = 'open'.
After a large delete
Deleted rows free no disk space for the operating system. VACUUM marks the space reusable inside the table, and autovacuum normally does this for you. After a very large delete, run VACUUM (ANALYZE) orders; so the planner statistics catch up. Returning disk space to the operating system needs VACUUM FULL or a table rewrite, and both take an exclusive lock on the table.
Common mistakes
- Running
EXPLAIN ANALYZEon a realUPDATEorDELETEwithout a transaction and rollback. - Forgetting an index on the foreign key column and then wondering why deleting one parent row is slow.
- Adding indexes on every column "for speed." Each extra index slows every update that touches its column.
- Batching without a stable order, which produces lock waits and deadlocks between jobs.
- Expecting rows in
FROMorUSINGtables to be locked. They are not.
Exercise
A batched UPDATE job sets status = 'archived' on orders of closed customers, 5000 rows at a time, committing after each batch. It never finishes and the log shows 5000 rows updated every time. What is wrong, and how do you fix it?
Show answer
The batch selection does not exclude rows that were already updated, so each iteration picks the same rows again and rewrites them. Add a condition that rows already changed no longer match, for example AND o.status <> 'archived' in the batch subquery (or IS DISTINCT FROM 'archived' if the column can be NULL). Then each batch removes rows from the candidate set, and the loop ends when zero rows are updated.
Exercise
Your DELETE FROM orders AS o USING customers AS c WHERE o.customer_id = c.id AND c.status = 'closed' is running. Which of these can other sessions still do on customers during the delete: read rows, update a customer's status, run ALTER TABLE customers ADD COLUMN? Explain.
Show answer
They can read rows and update a customer's status, because the statement takes only an ACCESS SHARE lock on customers and does not lock its rows. The status change will not affect your running statement, which uses its own snapshot. ALTER TABLE ... ADD COLUMN needs an ACCESS EXCLUSIVE lock, which conflicts with ACCESS SHARE, so it waits until the delete finishes.