Sub topic 1
MVCC: why readers do not block writers
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), can run transactions with BEGIN, COMMIT and ROLLBACK, and can open two psql sessions against the same database.
How MVCC lets readers run alongside writers
PostgreSQL uses multiversion concurrency control (MVCC). When a row changes, PostgreSQL keeps the old version and writes a new one. Each query reads a snapshot, so a SELECT sees a consistent view without waiting for an UPDATE that is still in progress. Readers do not block writers, and writers do not block readers.
MVCC does not remove the need for locks. Two writers that change the same row still need to take turns, and schema changes still need protection from concurrent queries.
Locks last until the end of the transaction
A lock taken inside a transaction stays held until COMMIT or ROLLBACK. Short transactions release locks sooner, which reduces waiting for other sessions.
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- The row lock on id = 1 is held here until COMMIT or ROLLBACK.
COMMIT;Table-level lock modes and which ones conflict
Each statement takes a table lock that declares what it intends to do. Two common modes are:
| Lock mode | Taken by | Conflicts with |
|---|---|---|
| ACCESS SHARE | SELECT | ACCESS EXCLUSIVE only |
| ROW EXCLUSIVE | INSERT, UPDATE, DELETE | SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE |
| ACCESS EXCLUSIVE | ALTER TABLE, DROP TABLE, LOCK TABLE (default mode) | Every other mode, including ACCESS SHARE |
Because SELECT takes ACCESS SHARE, it conflicts only with ACCESS EXCLUSIVE. Schema changes that need ACCESS EXCLUSIVE therefore wait for reads and block them.
Row-level locks and SELECT ... FOR UPDATE
A plain SELECT takes no row lock. To lock rows you intend to change, use SELECT ... FOR UPDATE:
-- Session A
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- Session B (waits until session A commits or rolls back)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;FOR UPDATE blocks other FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and UPDATE calls on the same row. FOR NO KEY UPDATE is a weaker lock for updates that do not change key columns, and it lets FOR KEY SHARE pass through. Use FOR UPDATE when you plan to change the row.
> Note: Test each lock with two psql sessions to see the waiting behavior directly.
Exercise
Session A runs SELECT ... FOR UPDATE on row 1 and does not commit yet. Session B runs a plain SELECT on row 1. Does Session B wait?
Show answer
No. A plain SELECT takes ACCESS SHARE on the table and reads the old snapshot of the row, so it does not wait for the row lock.