Video in progress
How do FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE differ?
These are four row-level lock modes, from strongest to weakest. FOR UPDATE prepares to delete a row or change its key, and FOR NO KEY UPDATE is for an UPDATE that doesn't touch the key. The FK check takes FOR KEY SHARE, and it blocks only a key change.
📖 Answer
The conflict table (✕ means they block each other):
| KEY SHARE | SHARE | NO KEY UPDATE | UPDATE | |
|---|---|---|---|---|
| FOR KEY SHARE | ✕ | |||
| FOR SHARE | ✕ | ✕ | ||
| FOR NO KEY UPDATE | ✕ | ✕ | ✕ | |
| FOR UPDATE | ✕ | ✕ | ✕ | ✕ |
Which mode does a plain UPDATE take? If the columns in a unique index don't change, FOR NO KEY UPDATE, otherwise FOR UPDATE. DELETE always takes FOR UPDATE.
Why this difference matters, with an FK example:
-- T1
BEGIN;
INSERT INTO order_item (order_id, ...) VALUES (42, ...);
-- the FK check puts FOR KEY SHARE on orders(42)
-- T2
UPDATE orders SET status = 'PAID' WHERE id = 42;
-- takes FOR NO KEY UPDATE, which doesn't conflict with KEY SHARE, so it doesn't wait
Up to PostgreSQL 9.3 the FK check took FOR SHARE, and in such cases updating the parent row was blocked; many deadlocks came from that.
A practical tip: if you lock a row only to change its non-key columns, write FOR NO KEY UPDATE instead of FOR UPDATE. Then inserting child rows that reference that row doesn't have to wait.
To see who is blocking whom: SELECT pid, pg_blocking_pids(pid), wait_event_type, query FROM pg_stat_activity WHERE wait_event_type = 'Lock';.
Sign up to mark studied questions and save your progress.