For Update Nowait Fail Fast

FOR UPDATE NOWAIT fails immediately with lock_not_available when another transaction holds the row, choosing a loud failure over unbounded queue waiting.

SqlResilience

Code

snippet
-- FOR UPDATE NOWAIT:行被别人持有时不排队,立刻报 55P03 lock_not_available。
-- 适合"宁可失败也不无限等待"的快速失败场景
CREATE TABLE payouts (id int PRIMARY KEY, status text NOT NULL, cents int NOT NULL);
INSERT INTO payouts VALUES (1, 'pending', 5000);

BEGIN;
-- 自己拿锁:查询立刻返回,行在本事务内被锁住
SELECT id FROM payouts WHERE id = 1 FOR UPDATE NOWAIT;
UPDATE payouts SET status = 'processing' WHERE id = 1;
COMMIT;

-- 另一个事务此刻抢同一行会直接失败:
-- BEGIN;
-- SELECT id FROM payouts WHERE id = 1 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "payouts"  (SQLSTATE 55P03)
-- 不带 NOWAIT 的 FOR UPDATE 会一直等到对方事务结束

-- 对照记忆:SKIP LOCKED 是"跳过被锁的行继续干别的",
-- NOWAIT 是"整条语句立刻失败",两者都不等待

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with payouts and nowait among the objects involved.

Concretely, the SQL combines: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the payouts table.

Statements that matter

SELECT id FROM payouts WHERE id = 1 FOR UPDATE NOWAIT;
UPDATE payouts SET status = 'processing' WHERE id = 1;
CREATE TABLE payouts (id int PRIMARY KEY, status text NOT NULL, cents int NOT NULL);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`payouts`, `nowait`.