NOWAIT and SKIP LOCKED
Overview and setup
PostgreSQL NOWAIT returns an error if a requested row lock cannot be obtained immediately; SKIP LOCKED omits locked rows. Both are options of locking SELECT. They affect row locking, not the ordinary table lock acquisition. SKIP LOCKED can be useful for competing queue consumers but produces an incomplete view and is not appropriate for general consistent reporting.
Use a fresh disposable file database initialized with versions/v56/locking-fixture.sql. Enable WAL with PRAGMA journal_mode=WAL; before opening two independent private-cache connections A and B. Use driver autocommit, no implicit transaction, zero busy timeout, and fully fetch each query result. Follow steps in order; the included Python validator automates this. Never use production data.
First two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session B
BEGIN IMMEDIATE;Observed error: SQLITE_BUSY
3. Session A
COMMIT;4. Session B
BEGIN IMMEDIATE;5. Session B
COMMIT;How it works
SQLite has neither clause. The zero-timeout writer test demonstrates immediate contention, not NOWAIT row semantics. A bounded single-statement UPDATE with RETURNING claims the smallest ready job; B must wait or retry after A releases the database writer slot. The example assigns jobs 1 and 2 separately. Production queues also need leases, retries, recovery of abandoned work and idempotent processing. A committed claim does not prove the job ran successfully.
Second two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session A
UPDATE lock_job SET status='claimed',worker='A' WHERE id=(SELECT id FROM lock_job WHERE status='ready' ORDER BY id LIMIT 1) AND status='ready' RETURNING id;Observed rows: [[1]]
3. Session B
BEGIN IMMEDIATE;Observed error: SQLITE_BUSY
4. Session A
COMMIT;5. Session B
BEGIN IMMEDIATE;6. Session B
UPDATE lock_job SET status='claimed',worker='B' WHERE id=(SELECT id FROM lock_job WHERE status='ready' ORDER BY id LIMIT 1) AND status='ready' RETURNING id;Observed rows: [[2]]
7. Session B
COMMIT;8. Session A
SELECT id,status,worker FROM lock_job ORDER BY id;Observed rows: [[1, "claimed", "A"], [2, "claimed", "B"], [3, "ready", null]]
Practice and mistakes
Practice: after both claims, execute a third and fourth claim. Hint 1: only job 3 remains ready. Hint 2: the fourth RETURNING result is empty. Mistake: treating a skipped row as permanently absent or assuming zero wait for table locks.