Sub topic 4
Row-Level Locks and `SELECT ... FOR UPDATE`
Assume you know basic SQL, transactions, primary and foreign keys, and how to use two concurrent psql sessions. This chapter focuses on how transactions protect individual rows while they read or change them.
Why row-level locks matter
PostgreSQL uses multiversion concurrency control (MVCC), so ordinary reads usually do not block ordinary writes. A query can read a committed row version while another transaction creates a newer version.
Some operations need stronger protection. For example, an application might:
- Read an account balance.
- Check that the balance is large enough.
- Update the balance.
Without a row lock, another transaction could change the balance between steps 1 and 3. SELECT ... FOR UPDATE locks the selected rows until the transaction ends.
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts (id, balance)
VALUES (1, 100), (2, 100);Run this setup once. Then use two database sessions:
-- Session A
BEGIN;
SELECT id, balance
FROM accounts
WHERE id = 1
FOR UPDATE;
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
-- Keep the transaction open while testing Session B.
COMMIT;-- Session B
BEGIN;
UPDATE accounts
SET balance = balance + 5
WHERE id = 1;
-- This statement waits until Session A commits or rolls back.
COMMIT;The lock belongs to the transaction, not just to the SELECT statement. Session B waits because its update needs a conflicting row lock. A rollback releases the lock just as a commit does.
The four row-lock clauses
PostgreSQL provides four locking clauses. They differ mainly in what later operations they allow.
| Clause | Typical purpose | Protects against |
|---|---|---|
| `FOR UPDATE` | Lock rows that the transaction may modify or delete | Other row-locking operations, updates, and deletes |
| `FOR NO KEY UPDATE` | Lock rows for updates that do not change key columns | Competing updates and deletes, while allowing key-share checks |
| `FOR SHARE` | Hold a shared read lock on rows | Updates, deletes, and stronger row locks |
| `FOR KEY SHARE` | Protect a referenced key, often during foreign-key checks | Deletes and updates that change the referenced key |
FOR UPDATE is the strongest and most common choice when your code will change or delete the selected rows. FOR NO KEY UPDATE is useful when the transaction changes ordinary columns but not a primary key or another key referenced by a foreign key.
FOR SHARE allows compatible shared readers to hold the same rows. FOR KEY SHARE is weaker. It permits ordinary non-key updates, but prevents another transaction from deleting the row or changing the referenced key.
BEGIN;
SELECT id, balance
FROM accounts
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
-- Validate the balances after taking the locks.
UPDATE accounts
SET balance = balance - 10
WHERE id = 1;
UPDATE accounts
SET balance = balance + 10
WHERE id = 2;
COMMIT;Common errors
A FOR UPDATE clause does not lock every row in a table. It locks only rows returned by the query. A missing or broad WHERE clause can therefore lock more rows than intended.
The clause also does not automatically protect later queries. Keep the read, validation, and write in the same transaction. Commit as soon as the protected work finishes.
Locks can be acquired through joins. PostgreSQL normally locks rows from the tables named in the locking clause. Use FOR UPDATE OF accounts when a join should lock rows from only one table.
Locking flow
Exercise
Which clause is usually appropriate when a transaction will change an account balance but will not change the account's primary key: FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, or FOR KEY SHARE?
Show answer
FOR NO KEY UPDATE is the more specific choice. FOR UPDATE also prevents the conflicting operation, but it takes a stronger lock than necessary.