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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Which tables does the SQL touch?
- `payouts`, `nowait`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.