Sub topic 14
Indexes, Locks, and Batching
Assume you know basic SELECT, WHERE, INNER JOIN, single-table UPDATE and DELETE, aliases, and primary and foreign keys. This chapter focuses on making PostgreSQL join-based modifications faster and safer.
Indexes that support the change
An index helps PostgreSQL find rows without scanning an entire table. For UPDATE ... FROM and DELETE ... USING, index both the join columns and the columns used to filter rows.
For example, this statement joins orders to customers and filters by customer status:
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';Useful indexes may include:
| Query need | Possible index |
|---|---|
| Find orders for a customer | `orders (customer_id)` |
| Find closed customers | `customers (status, id)` |
| Find open orders while batching | `orders (status, id)` |
A primary key already creates an index, so customers.id and orders.id do not need separate indexes. PostgreSQL does not automatically create an index on every foreign-key column.
Indexes speed up row selection, but they also consume storage and make writes more expensive. Check the plan before and after adding one:
EXPLAIN
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';Run ANALYZE orders; and ANALYZE customers; after a large data change so the planner has current statistics.
Locks and contention
An UPDATE or DELETE takes a table-level lock that allows ordinary reads but coordinates with other writers. It also locks each row it changes. If another transaction already holds a conflicting row lock, your statement waits.
The longer the transaction remains open, the longer those locks remain available to block other work.
For special cases, NOWAIT fails immediately instead of waiting, while SKIP LOCKED ignores rows currently locked by another transaction. These options are useful for worker queues, but skipped rows are not proof that no matching rows exist.
Batching large changes
Changing millions of rows in one transaction can create long lock waits, a large write-ahead log, and difficult rollback work. Process a limited number of rows, inspect the result, and commit each batch from the client.
This example selects 100 unlocked orders before updating them:
WITH batch AS (
SELECT o.id
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE c.status = 'closed'
AND o.status = 'open'
ORDER BY o.id
FOR UPDATE OF o SKIP LOCKED
LIMIT 100
)
UPDATE orders AS o
SET status = 'cancelled'
FROM batch
WHERE o.id = batch.id
RETURNING o.id;The ORDER BY makes normal batch processing predictable. FOR UPDATE locks the selected order rows. SKIP LOCKED lets another worker process rows that this transaction cannot currently obtain.
Repeat the statement in a new transaction until it returns no rows. If exact accounting matters, record each returned identifier or use a separate audit table.
Practical checklist
- Index join columns and selective filter columns.
- Use
EXPLAINbefore running a large modification. - Run
ANALYZEafter major data changes. - Preview a batch with
SELECTbefore changing it. - Use short transactions and a fixed batch size.
- Set suitable
lock_timeoutandstatement_timeoutvalues. - Treat
SKIP LOCKEDas a concurrency tool, not a complete result count.
Exercise
Which index is most directly useful when deleting orders with WHERE orders.customer_id = customers.id?
Show answer
An index on orders (customer_id). The customer primary-key index already supports the lookup of customers.id; add a status or ordering column only when the complete query benefits from it.