← Back to PostgreSQL, page 3

postgresql-0052 · Medium mid

Lock a row with SELECT ... FOR UPDATE, and fail fast with NOWAIT instead of waiting.

SELECT ... FOR UPDATE locks the selected rows until the transaction ends, so other transactions wanting to update or lock them wait. NOWAIT makes the second request fail immediately with an error instead of waiting, and lock_timeout sets a maximum wait. FOR NO KEY UPDATE and FOR SHARE are weaker lock modes for less conflicting cases.

Full answer

Tables and rows used here:

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
sql
BEGIN; SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE;

Result:

text
 id | balance
----+---------
 1  | 500
(1 row)

In a second session:

sql
SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

Output:

text
ERROR:  could not obtain lock on row in relation "accounts"

In a second session:

sql
SELECT id, balance FROM accounts WHERE id = 1;

PostgreSQL returns:

text
 id | balance
----+---------
 1  | 500
(1 row)

In a second session:

sql
SELECT id FROM accounts WHERE id = 2 FOR UPDATE NOWAIT;

Result on PostgreSQL 17:

text
 id
----
 2
(1 row)
sql
UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;

Result:

text
COMMIT

In a second session:

sql
SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

Output:

text
 id | balance
----+---------
 1  | 400
(1 row)

While A holds the lock, B's FOR UPDATE NOWAIT fails with 'could not obtain lock on row in relation "accounts"'. A plain SELECT is not blocked and still reads the committed value 500, because readers never wait for row locks in PostgreSQL. Locking a different row succeeds. After A commits, B can lock the row and sees 400. NOWAIT suits user-facing actions such as 'someone else is editing this order', where waiting is worse than a clear message.

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);

BEGIN; SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE;

-- session B
SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

-- session B
SELECT id, balance FROM accounts WHERE id = 1;

-- session B
SELECT id FROM accounts WHERE id = 2 FOR UPDATE NOWAIT;

UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;

-- session B
SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • FOR UPDATE locks rows until commit
  • NOWAIT errors instead of waiting
  • Plain reads are never blocked
  • Locks are per row
  • lock_timeout bounds waiting

Common mistakes

  • Holding row locks across user think time
  • Expecting plain SELECTs to block

Follow-ups

  • When is FOR NO KEY UPDATE enough?
  • How do row locks interact with foreign keys?

Tips

  • Show that readers are not blocked