Sub topic 3
Table-level lock modes and which ones conflict
This chapter assumes you can run two concurrent psql sessions. It also assumes you know that a lock taken inside a transaction is held until COMMIT or ROLLBACK, and that you have the accounts table from the earlier chapters. After reading, you should be able to predict whether two statements will block each other without running them.
Every statement takes a table lock
PostgreSQL takes a table-level lock for every statement that touches a table, including plain SELECT. Most of the time you never notice, because the lock modes taken by everyday statements do not conflict with each other. A conflict only appears when one statement needs a mode that is incompatible with a mode another transaction already holds.
There are eight table-level lock modes. Their names are historical and can mislead. "ROW EXCLUSIVE" does not mean the statement locks rows exclusively, and it is a table-level mode. Row locks are a separate mechanism, covered in the next chapter.
The eight modes and what takes them
The modes run from weakest to strongest. The table lists the common statements that acquire each one.
| Mode | Typical statements |
|---|---|
| ACCESS SHARE | `SELECT` |
| ROW SHARE | `SELECT ... FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE` |
| ROW EXCLUSIVE | `INSERT`, `UPDATE`, `DELETE`, `MERGE` |
| SHARE UPDATE EXCLUSIVE | `VACUUM` (without `FULL`), `ANALYZE`, `CREATE INDEX CONCURRENTLY`, some `ALTER TABLE` forms such as `VALIDATE CONSTRAINT` |
| SHARE | `CREATE INDEX` (without `CONCURRENTLY`) |
| SHARE ROW EXCLUSIVE | `CREATE TRIGGER`, `ALTER TABLE ... ADD FOREIGN KEY` |
| EXCLUSIVE | `REFRESH MATERIALIZED VIEW CONCURRENTLY` |
| ACCESS EXCLUSIVE | `DROP TABLE`, `TRUNCATE`, `VACUUM FULL`, `CLUSTER`, `REINDEX`, `REFRESH MATERIALIZED VIEW`, most `ALTER TABLE` forms |
LOCK TABLE with no mode specified takes ACCESS EXCLUSIVE.
Two groups matter most in practice:
- The three weakest modes (ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE) are what normal queries and data changes use. They are compatible with each other, so ordinary reads and writes from many sessions run side by side.
- ACCESS EXCLUSIVE conflicts with every mode, including ACCESS SHARE. While one transaction holds it, even a plain
SELECTon that table waits.
The conflict matrix
Two transactions can both hold locks on the same table only if their modes do not conflict. A transaction never conflicts with itself, so one transaction can hold several modes on the same table.
In this matrix, X means the two modes conflict. The abbreviations are AS (ACCESS SHARE), RS (ROW SHARE), RE (ROW EXCLUSIVE), SUE (SHARE UPDATE EXCLUSIVE), S (SHARE), SRE (SHARE ROW EXCLUSIVE), E (EXCLUSIVE) and AE (ACCESS EXCLUSIVE).
| Held / Requested | AS | RS | RE | SUE | S | SRE | E | AE |
|---|---|---|---|---|---|---|---|---|
| AS | X | |||||||
| RS | X | X | ||||||
| RE | X | X | X | X | ||||
| SUE | X | X | X | X | X | |||
| S | X | X | X | X | X | |||
| SRE | X | X | X | X | X | X | ||
| E | X | X | X | X | X | X | X | |
| AE | X | X | X | X | X | X | X | X |
The matrix is symmetric: if A conflicts with B, then B conflicts with A. You do not need to memorize it. These rules reproduce most of it:
- ACCESS EXCLUSIVE conflicts with everything.
- ACCESS SHARE conflicts only with ACCESS EXCLUSIVE.
- ROW EXCLUSIVE conflicts with SHARE and anything stronger, so
UPDATEand non-concurrentCREATE INDEXblock each other. - SHARE UPDATE EXCLUSIVE conflicts with itself, so only one
VACUUM,ANALYZEorCREATE INDEX CONCURRENTLYcan run on a table at a time. - SHARE does not conflict with itself, so two
CREATE INDEXstatements can build in parallel.
See it with two sessions
LOCK TABLE lets you take a mode explicitly. This demonstrates rule 3 on the accounts table.
-- Session A
BEGIN;
LOCK TABLE accounts IN SHARE MODE;
-- Session B: ACCESS SHARE does not conflict with SHARE, so this returns rows
SELECT * FROM accounts;
-- Session B: ROW EXCLUSIVE conflicts with SHARE, so this waits
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
-- Session A
COMMIT; -- session B's UPDATE now proceedsWhile session B is waiting, you can list the table locks held and requested in a third session.
SELECT pid, mode, granted
FROM pg_locks
WHERE locktype = 'relation'
AND relation = 'accounts'::regclass
ORDER BY granted DESC, pid;Session A shows ShareLock with granted = true. Session B shows RowExclusiveLock with granted = false. The names in pg_locks.mode use the CamelCase form of the mode names, for example AccessShareLock and ShareUpdateExclusiveLock.
You can also see what your own statements take. Inside a transaction, run a statement and then inspect your session's locks.
BEGIN;
UPDATE accounts SET balance = balance WHERE id = 1;
SELECT locktype, relation::regclass AS relation, mode, granted
FROM pg_locks
WHERE pid = pg_backend_pid()
AND locktype = 'relation';
ROLLBACK;The result includes RowExclusiveLock on accounts and on its primary key index. Index locks appear because the statement also touches the index.
Locks are held until the transaction ends
A table lock is released at COMMIT or ROLLBACK, not when the statement that took it finishes. Outside an explicit transaction, each statement is its own transaction, so the lock lasts for that one statement.
This is why an open transaction is risky. If a session runs BEGIN; SELECT * FROM accounts; and then sits idle, it holds ACCESS SHARE on accounts for as long as it stays open. ACCESS SHARE is harmless to other readers and writers, but it blocks any request for ACCESS EXCLUSIVE.
Why a weak lock can block everyone
Lock requests wait in a queue. A request that conflicts with a held lock waits. A later request that conflicts with a waiting request also waits, even if it would be compatible with every lock currently held.
Consider this sequence:
- Session A starts a transaction and runs a
SELECTonaccounts. It holds ACCESS SHARE and stays open. - Session B runs
ALTER TABLE accounts ADD COLUMN note text. It needs ACCESS EXCLUSIVE, which conflicts with A's lock, so it waits. - Session C runs a plain
SELECTonaccounts. ACCESS SHARE does not conflict with A's lock. It does conflict with B's waiting ACCESS EXCLUSIVE request, so C waits behind B.
The ALTER TABLE itself changes nothing until it gets its lock, but the table is effectively unavailable to every new query. This is the main failure mode of schema migrations, and it is why the lock queue gets its own chapter. A later chapter shows how lock_timeout limits the damage.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;If the lock is not granted within two seconds, the ALTER TABLE fails with an error and leaves the queue, and the waiting SELECT statements proceed.
Choosing and predicting
When you are unsure whether two operations will conflict, work through these steps:
- Find the mode each statement takes. The statement's page in the PostgreSQL documentation lists it, and the explicit-locking chapter has the full table.
- Look up the pair in the matrix. If there is no
X, they run concurrently. - Remember the queue. If a third request is already waiting, a compatible request can still wait behind it.
Some examples:
UPDATEandUPDATEon the same table: ROW EXCLUSIVE with ROW EXCLUSIVE, no conflict. They only wait if they target the same row, which is a row-level lock question.CREATE INDEXandINSERT: SHARE with ROW EXCLUSIVE, conflict. Writes wait for the index build.CREATE INDEX CONCURRENTLYtakes SHARE UPDATE EXCLUSIVE instead, which does not conflict with writes. It takes longer and cannot run inside a transaction block.VACUUMandSELECT: SHARE UPDATE EXCLUSIVE with ACCESS SHARE, no conflict.VACUUM FULLandSELECT: ACCESS EXCLUSIVE with ACCESS SHARE, conflict. This is whyVACUUM FULLis rarely run on busy tables.ALTER TABLE ... ADD FOREIGN KEY: SHARE ROW EXCLUSIVE on both tables, which blocks writes to both while it runs.
Common mistakes
- Assuming
SELECTnever blocks. It does not block on writers, but it can be blocked by ACCESS EXCLUSIVE, including a queued one. - Running DDL without a timeout. Most
ALTER TABLEforms need ACCESS EXCLUSIVE. Withoutlock_timeout, one long transaction can stall all traffic to the table. - Mixing up table and row locks.
SELECT ... FOR UPDATEtakes ROW SHARE on the table plus row locks on the matching rows. The table-level mode is weak, so it does not stop other sessions from reading or updating other rows. - Forgetting that locks outlive statements. Check for transactions left open by clients and connection pools.
Exercise
Session A runs BEGIN; CREATE INDEX accounts_balance_idx ON accounts (balance); and has not committed. Session B runs SELECT * FROM accounts; and then session C runs INSERT INTO accounts VALUES (3, 50);. Which of B and C wait, and why?
Show answer
Only C waits. A's non-concurrent CREATE INDEX holds a SHARE lock. B's SELECT takes ACCESS SHARE, which does not conflict with SHARE, so B returns rows. C's INSERT takes ROW EXCLUSIVE, which conflicts with SHARE, so C waits until A commits or rolls back.
Exercise
A long-running transaction in session A has read from accounts and is still open. Session B starts ALTER TABLE accounts ADD COLUMN note text and waits. Why do new plain SELECT statements from session C also hang, and how can you stop B from causing that?
Show answer
A holds ACCESS SHARE, and the ALTER TABLE needs ACCESS EXCLUSIVE, so B waits. C's ACCESS SHARE request conflicts with B's queued ACCESS EXCLUSIVE request, so C queues behind B even though it does not conflict with A. Setting a short lock_timeout in the migration (for example SET LOCAL lock_timeout = '2s') makes B give up with an error instead of waiting, which releases C and the other queued sessions.