table lock modes
eight modes from ACCESS SHARE to ACCESS EXCLUSIVE, and the matrix that decides who waits.
- address
- everything.locking.table_lock_modes
- part
- part 15, locks and concurrency control
- chapter
- chapter 3 of 10
- reading time
- 8 min
every statement takes a table lock before it touches a table, in one of eight modes, from ACCESS SHARE (a SELECT) to ACCESS EXCLUSIVE (most ALTER TABLEs, DROP, VACUUM FULL). a fixed conflict matrix decides which modes can be held at the same time. most of it exists so that reads and writes never block each other, and so that DDL blocks as little as it can get away with.
the picture
you know how a SELECT and an UPDATE on the same table run side by side without anyone waiting, but an ALTER TABLE can freeze everything? same lock manager, different modes.
think of a library reading room. readers walk in and out freely (ACCESS SHARE). people writing notes in the margins can work together too, as long as nobody's rebinding the books (ROW EXCLUSIVE). the binder who takes every book apart (ACCESS EXCLUSIVE) needs the room empty. the eight modes are the house rules for who can be in the room with whom.
| held ↓ wanted → | AS | RS | RX | SUX | S | SRX | X | AX |
|---|---|---|---|---|---|---|---|---|
| × | ||||||||
| × | × | |||||||
| × | × | × | × | |||||
| × | × | × | × | × | ||||
| × | × | × | × | × | ||||
| × | × | × | × | × | × | |||
| × | × | × | × | × | × | × | ||
| × | × | × | × | × | × | × | × |
hover a mode: × marks what it can't share a table with.
read it along the diagonal first. ACCESS SHARE, ROW SHARE and ROW EXCLUSIVE don't conflict with themselves: many readers, many writers, all at once. from SHARE UPDATE EXCLUSIVE down, modes start conflicting with copies of themselves, which is how postgres says "only one of these at a time": one VACUUM per table, one CREATE INDEX CONCURRENTLY, one ALTER. SHARE is the odd one: it's compatible with itself but not with ROW EXCLUSIVE, so two plain CREATE INDEXes can run together, but no writes while either runs.
the names are historical and misleading ("ROW EXCLUSIVE" is a table lock, not a row lock). ignore the words and learn the statements.
which statement takes which
no need to memorize the manual's list: ask the lock manager. the function below runs a statement, reads its own locks on accounts out of pg_locks, and throws the statement's work away (a subtransaction that rolls back releases the locks it took, and undoes the change).
CREATE TABLE accounts (id int PRIMARY KEY, owner text NOT NULL, balance numeric(12,2) NOT NULL);
ALTER TABLE accounts ADD CONSTRAINT nonneg CHECK (balance >= 0) NOT VALID;
CREATE TABLE transfers (id int PRIMARY KEY, src int NOT NULL, amount numeric(12,2) NOT NULL);
CREATE FUNCTION lock_taken(stmt text) RETURNS text LANGUAGE plpgsql AS $$
DECLARE m text;
BEGIN
BEGIN
EXECUTE stmt;
SELECT string_agg(mode, ', ' ORDER BY mode) INTO m FROM pg_locks
WHERE pid = pg_backend_pid() AND locktype = 'relation'
AND relation = 'accounts'::regclass;
RAISE EXCEPTION USING ERRCODE = 'P0001'; -- undo the statement
EXCEPTION WHEN raise_exception THEN NULL;
END;
RETURN m;
END $$;
SELECT stmt, lock_taken(stmt) AS lock FROM (VALUES
(1, 'SELECT * FROM accounts'),
(2, 'SELECT * FROM accounts FOR UPDATE'),
(3, 'UPDATE accounts SET balance = 0'),
(4, 'ANALYZE accounts'),
(5, 'ALTER TABLE accounts VALIDATE CONSTRAINT nonneg'),
(6, 'ALTER TABLE accounts SET (fillfactor = 70)'),
(7, 'CREATE INDEX ON accounts (owner)'),
(8, 'ALTER TABLE transfers ADD FOREIGN KEY (src) REFERENCES accounts'),
(9, 'LOCK TABLE accounts IN EXCLUSIVE MODE'),
(10, 'ALTER TABLE accounts ADD COLUMN note text'),
(11, 'ALTER TABLE accounts ADD CONSTRAINT pos CHECK (balance >= 0) NOT VALID')
) AS s(n, stmt) ORDER BY n;| stmttext | locktext |
|---|---|
| SELECT * FROM accounts | AccessShareLock |
| SELECT * FROM accounts FOR UPDATE | RowShareLock |
| UPDATE accounts SET balance = 0 | RowExclusiveLock |
| ANALYZE accounts | ShareUpdateExclusiveLock |
| ALTER TABLE accounts VALIDATE CONSTRAINT nonneg | ShareUpdateExclusiveLock |
| ALTER TABLE accounts SET (fillfactor = 70) | ShareUpdateExclusiveLock |
| CREATE INDEX ON accounts (owner) | ShareLock |
| ALTER TABLE transfers ADD FOREIGN KEY (src) REFERENCES accounts | AccessShareLock, RowShareLock, ShareRowExclusiveLock |
| LOCK TABLE accounts IN EXCLUSIVE MODE | ExclusiveLock |
| ALTER TABLE accounts ADD COLUMN note text | AccessExclusiveLock |
| AccessExclusiveLock |
that's the ladder, weakest to strongest. a few things worth noticing:
SELECT ... FOR UPDATEtakes ROW SHARE on the table. the row locks themselves are somewhere else entirely (how row locks are stored).- ANALYZE, VALIDATE CONSTRAINT and
SET (fillfactor = ...)take SHARE UPDATE EXCLUSIVE: reads and writes carry on. that's whyADD CONSTRAINT ... NOT VALIDthenVALIDATEis the polite way to add a constraint to a big table. the first step is ACCESS EXCLUSIVE (row 11) but instant; the slow scan happens in the second, under the weak lock. - a foreign key takes SHARE ROW EXCLUSIVE on the table it references (the ACCESS SHARE and ROW SHARE next to it come from the query that checks the existing rows). EXCLUSIVE is the one mode no common statement takes for you; you get it from
LOCK TABLE(and, per the manual, fromREFRESH MATERIALIZED VIEW CONCURRENTLY). - ADD COLUMN is ACCESS EXCLUSIVE even though it's instant. instant is fine. waiting is the problem.
CREATE INDEX vs CONCURRENTLY
plain CREATE INDEX takes SHARE: readers fine, writers wait for the whole build. CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, which lets writes in, and pays for it with two table scans and some waiting of its own:
- T1SHAREaccounts
- T1ExclusiveLockvxid 4/4
T1 builds an index inside a transaction, so its lock stays visible. CREATE INDEX takes SHARE on the table.
/* T1 */ BEGIN; UPDATE accounts SET balance = balance - 1 WHERE id = 1;
/* T1 */ -- ... goes to lunch
/* T2 */ CREATE INDEX CONCURRENTLY accounts_owner ON accounts (owner);VACUUM vs VACUUM FULL
same keyword, opposite ends of the matrix:
- T1ACCESS SHAREaccounts
T1 reads accounts in an open transaction: ACCESS SHARE.
plain VACUUM cleans pages in place and never blocks reads or writes (VACUUM). VACUUM FULL is a rewrite: while it runs, the table is gone for everyone.
upgrades
a transaction keeps every lock it takes until it ends, and a stronger request on the same table doesn't replace the weaker one, it's added next to it. so BEGIN; SELECT ...; ALTER TABLE ... holds ACCESS SHARE and ACCESS EXCLUSIVE. that's fine alone and a deadlock when two transactions do it at once: each waits for the other's ACCESS SHARE. the lock queue has the capture.
it's also why SHARE ROW EXCLUSIVE exists. SHARE is self-compatible, so two transactions that take SHARE and later want something stronger deadlock the same way. SHARE ROW EXCLUSIVE is SHARE that conflicts with itself, so the second one waits up front instead.
keylines
- eight table lock modes. the matrix says which pairs can be held at once.
- SELECT is ACCESS SHARE, DML is ROW EXCLUSIVE, they never conflict.
- SHARE UPDATE EXCLUSIVE is the "maintenance that lets you keep working" mode: VACUUM, ANALYZE, CONCURRENTLY, VALIDATE.
- ACCESS EXCLUSIVE conflicts with everything: ALTER, DROP, TRUNCATE, VACUUM FULL.
- locks are held until the transaction ends, and a stronger one is added, not swapped. two upgraders deadlock.