Full answer
Tables and rows used here:
sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE order_events (order_id int REFERENCES orders(id), note text);
INSERT INTO orders VALUES (1, 'new');sql
BEGIN; SELECT id FROM orders WHERE id = 1 FOR UPDATE;Output:
text
id
----
1
(1 row)In a second session:
sql
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');PostgreSQL returns:
text
ERROR: canceling statement due to lock timeoutsql
ROLLBACK; BEGIN; SELECT id FROM orders WHERE id = 1 FOR NO KEY UPDATE;Result on PostgreSQL 17:
text
id
----
1
(1 row)In a second session:
sql
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');Result:
text
INSERT 0 1sql
UPDATE orders SET status = 'paid' WHERE id = 1; COMMIT; SELECT o.status, count(e.*) AS events FROM orders o LEFT JOIN order_events e ON e.order_id = o.id GROUP BY o.status;Output:
text
status | events
--------+--------
paid | 1
(1 row)While A holds FOR UPDATE on order 1, B's child insert waits for the key-share lock and gives up after 200 ms with a lock timeout. With FOR NO KEY UPDATE, the same insert succeeds at once, and A can still update the order's status. Code that locks a parent only to change non-key columns should therefore use FOR NO KEY UPDATE. The same conflict explains lock waits in high-traffic systems where one hot parent row, such as an account, receives many child inserts while being locked by other work.
sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE order_events (order_id int REFERENCES orders(id), note text);
INSERT INTO orders VALUES (1, 'new');
BEGIN; SELECT id FROM orders WHERE id = 1 FOR UPDATE;
-- session B
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');
ROLLBACK; BEGIN; SELECT id FROM orders WHERE id = 1 FOR NO KEY UPDATE;
-- session B
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');
UPDATE orders SET status = 'paid' WHERE id = 1; COMMIT; SELECT o.status, count(e.*) AS events FROM orders o LEFT JOIN order_events e ON e.order_id = o.id GROUP BY o.status;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Child inserts take FOR KEY SHARE on the parent
- FOR UPDATE blocks them
- FOR NO KEY UPDATE does not
- Plain UPDATEs of non-key columns use NO KEY UPDATE
- Hot parents cause lock waits
Common mistakes
- Using FOR UPDATE by habit for every parent lock
- Updating primary key columns casually
Follow-ups
- Which lock does DELETE take on the parent?
- How do you see lock waits in pg_stat_activity?
Tips
- Name FOR KEY SHARE