Sub topic 4
Row-level locks and SELECT ... FOR UPDATE
This chapter assumes you know basic SQL and transactions, can run two psql sessions side by side, and have read the earlier chapters on MVCC and on locks lasting until the end of a transaction. Table-level locks come in the previous chapter. This one covers row-level locks: what takes them, which ones conflict, and the surprises that come up in real code.
What a row lock protects
MVCC lets readers see a snapshot without blocking anyone. Two transactions that want to change the same row still need to take turns. A row-level lock enforces that turn-taking.
Row locks have these properties:
- They are taken per row. PostgreSQL has no lock escalation, so locking a million rows never turns into a table lock.
- They are held until the transaction commits or rolls back. Rolling back to a savepoint releases the row locks acquired after that savepoint.
- They never block plain
SELECT. Readers use their snapshot, as described in the MVCC chapter. - They block only other writers and other lockers of the same row.
UPDATE and DELETE take a row lock automatically. The first example from the plan shows this:
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B (blocks until session A commits or rolls back)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- Session A
COMMIT;Session B resumes after A's COMMIT. In the default READ COMMITTED level, it re-reads the newest version of the row and applies balance + 5 to 90, giving 95. No update is lost.
Locking rows explicitly with SELECT ... FOR
Sometimes you need to lock a row before you decide what to write. A read-then-write sequence without a lock has a race:
-- Both sessions run this, interleaved
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- both see 100
-- application computes 100 - 30 = 70
UPDATE accounts SET balance = 70 WHERE id = 1;
COMMIT;Both sessions write 70, and one withdrawal vanishes. This is a lost update. Adding FOR UPDATE to the SELECT fixes it:
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- the second session blocks here until this transaction ends
UPDATE accounts SET balance = 70 WHERE id = 1;
COMMIT;When the first transaction commits, the blocked SELECT returns the new balance (70), so the second withdrawal computes from the correct value. Where possible, a single atomic statement such as SET balance = balance - 30 is simpler. Use explicit locks when the application must inspect the row first.
The four row lock modes
PostgreSQL has four row-level modes, from strongest to weakest.
| Mode | Typical source | Meaning |
|---|---|---|
| `FOR UPDATE` | `DELETE`, `UPDATE` that changes a key column, explicit clause | Exclusive. The row may be deleted or have its key changed. |
| `FOR NO KEY UPDATE` | Ordinary `UPDATE` that leaves key columns alone, explicit clause | Exclusive for changes to non-key columns. |
| `FOR SHARE` | Explicit clause | Others may read-lock the row but not modify it. |
| `FOR KEY SHARE` | Foreign key checks, explicit clause | Others may modify non-key columns, but the key must not change or vanish. |
A "key column" here means a column in a unique index that can be the target of a foreign key. The weaker modes exist so that foreign keys do not get in the way of normal updates.
The conflict rules are:
| Requested mode (below) / Held mode (right) | KEY SHARE | SHARE | NO KEY UPDATE | UPDATE |
|---|---|---|---|---|
| `FOR KEY SHARE` | ok | ok | ok | conflict |
| `FOR SHARE` | ok | ok | conflict | conflict |
| `FOR NO KEY UPDATE` | ok | conflict | conflict | conflict |
| `FOR UPDATE` | conflict | conflict | conflict | conflict |
Read the table row by row: a FOR KEY SHARE request fails to proceed only if another transaction holds FOR UPDATE. A FOR UPDATE request conflicts with everything.
Foreign keys use FOR KEY SHARE
When you insert a child row, PostgreSQL takes FOR KEY SHARE on the referenced parent row. It stops the parent being deleted or re-keyed, but does not stop ordinary updates. Try it:
CREATE TABLE orders (
id int PRIMARY KEY,
account_id int NOT NULL REFERENCES accounts(id)
);
-- Session A
BEGIN;
INSERT INTO orders VALUES (1, 1); -- FOR KEY SHARE on accounts row 1
-- Session B
UPDATE accounts SET balance = balance + 1 WHERE id = 1; -- runs immediately
DELETE FROM accounts WHERE id = 1; -- blocks (FOR UPDATE)
-- Session A
ROLLBACK;The balance update is a FOR NO KEY UPDATE, which does not conflict with FOR KEY SHARE. The DELETE needs FOR UPDATE, so it waits. Before PostgreSQL 9.3, foreign key checks took FOR SHARE, and any parent-row update blocked behind child inserts. If you see old advice that foreign keys cause heavy contention, that is the source.
Choosing a mode
- Use
FOR UPDATEwhen you will delete the row or change its key. - Use
FOR NO KEY UPDATEwhen you will only change non-key columns. It lets concurrent child inserts proceed, so it is often the better choice for "lock, inspect, then update". - Use
FOR SHAREto ensure a row you read does not change before you commit, without excluding other readers who also lock it. Two sessions that both holdFOR SHAREand then try toUPDATEthe same row will deadlock, so use it with care. - Use
FOR KEY SHARErarely by hand. It is mostly the foreign key machinery.
How row locks are stored
Row locks are not kept in the shared lock table. PostgreSQL records them in the row version's header (the xmax field plus flag bits). The consequences:
- Locking many rows costs no shared memory.
SELECT ... FOR UPDATEon a large table can still write to many pages and generate I/O and WAL. - A
SELECT ... FOR UPDATEmodifies the page, so it dirties buffers even though no data changes. - A waiting session does not wait on a "row lock" entry. It waits for the transaction ID of the lock holder to finish. In
pg_locksyou will see atransactionidlock withgranted = false, not the row. Thepgrowlocksextension can show row-level lock holders directly. - Every explicit
FOR ...clause also takes aROW SHARElock on the table. It conflicts only withEXCLUSIVEandACCESS EXCLUSIVE, which is why a pendingALTER TABLEcan still queue behind your row-locking transaction.
Locking only some rows or tables
With joins, FOR UPDATE locks the rows from every table in the query unless you restrict it:
SELECT o.id, a.balance
FROM orders AS o
JOIN accounts AS a ON a.id = o.account_id
WHERE o.id = 1
FOR UPDATE OF o; -- lock only the orders row, leave accounts aloneWithout OF o, the accounts row is locked too, which can block unrelated work.
Other limits to know:
FOR UPDATEcannot be used withDISTINCT,GROUP BY,HAVING,UNION, or aggregate and window functions. Each result row must map to one real table row.- It cannot lock the nullable side of an outer join.
- Locks apply only to rows returned to the client or consumed by the cursor. With
LIMIT, PostgreSQL stops locking once it has enough rows, but the rows it examined and discarded before the sort may not be locked at all. Do not assume "all rows matching theWHERE" are locked when you also haveORDER BY ... LIMIT.
Gotchas under READ COMMITTED
After a lock wait ends, PostgreSQL re-checks the WHERE clause against the latest version of the row. If the row no longer matches, it is skipped. This matters for work-claiming queries:
-- Both sessions run this at the same time
BEGIN;
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE;Session A locks job 1 and then changes its status to done. Session B waited on job 1. When A commits, B re-checks job 1, sees it is no longer pending, and drops it. B then returns zero rows instead of moving on to job 2, even though other pending jobs exist. Your code must handle an empty result and retry, or use SKIP LOCKED (covered in a later chapter) to step over locked rows.
Under REPEATABLE READ and SERIALIZABLE, the behavior is different. If the locked row was changed by a transaction that committed after your snapshot, PostgreSQL does not re-read it. It aborts your transaction with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). Your application has to catch that error and retry the whole transaction.
Failing fast instead of waiting
By default a blocked FOR UPDATE waits forever. Two modifiers change that:
SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "accounts" (SQLSTATE 55P03)NOWAIT raises an error immediately if any selected row is locked. Plain lock_timeout gives the same SQLSTATE after a delay. Both are detailed in later chapters.
Common mistakes
- Locking too early. Taking
FOR UPDATEat the start of a long transaction, then doing slow work (network calls, user input), holds the lock for the whole duration. Lock as late as possible and commit quickly. - Assuming a plain
SELECTlocks. It does not. Another session can change the row between yourSELECTand yourUPDATE. - Locking in inconsistent order. If two transactions lock rows 1 and 2 in opposite orders, they deadlock. Lock in a fixed order, for example
ORDER BY id. - Using
FOR UPDATEwhereFOR NO KEY UPDATEsuffices. The stronger mode blocks child inserts through foreign keys for no benefit. - Forgetting that the lock outlives the statement. In
autocommitmode,SELECT ... FOR UPDATEreleases its lock as soon as the statement ends. The lock only protects you inside an explicitBEGIN ... COMMIT.
Exercise
Session A runs BEGIN; SELECT FROM accounts WHERE id = 1 FOR NO KEY UPDATE; and stays open. Which of these statements in session B block, and why? (1) SELECT FROM accounts WHERE id = 1; (2) INSERT INTO orders VALUES (2, 1); where orders.account_id references accounts(id); (3) SELECT * FROM accounts WHERE id = 1 FOR SHARE; (4) UPDATE accounts SET balance = 0 WHERE id = 1;
Show answer
Only (3) and (4) block. (1) is a plain read and uses the MVCC snapshot, so it never blocks. (2) takes FOR KEY SHARE on the accounts row, which does not conflict with FOR NO KEY UPDATE. (3) requests FOR SHARE, which conflicts with FOR NO KEY UPDATE. (4) is an ordinary UPDATE that does not touch a key column, so it needs FOR NO KEY UPDATE, which conflicts with the mode A already holds. Both wait until session A commits or rolls back.
Exercise
Two workers run SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1 FOR UPDATE under READ COMMITTED. The first claims job 1, marks it done, and commits while the second is waiting. What does the second worker get, and what should the code do?
Show answer
The second worker re-checks job 1 against its new version, sees status is no longer 'pending', and discards it. The query returns zero rows even if other pending jobs exist. The code should treat an empty result as "try again" (re-run the query) or use FOR UPDATE SKIP LOCKED so the second worker moves straight to the next unlocked pending row.