Select For Update Skip Locked
Claim a batch of jobs from a queue by locking only unlocked rows, letting concurrent workers drain the queue without blocking each other.
Code
WITH claimed AS (
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY created_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'processing', started_at = now()
WHERE id IN (SELECT id FROM claimed)
RETURNING id, payload;How the snippet works
What runs is SELECT / UPDATE, with jobs, skip and claimed as the object involved.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; a RETURNING clause that hands the affected rows back to the caller.
Applying it
The jobs table is the working surface here, and the LIMIT bounds each probe.
Statements that matter
WITH claimed AS (
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY created_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'processing', started_at = now()
WHERE id IN (SELECT id FROM claimed)
RETURNING id, payload;
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?
- The references are `jobs`, `skip`, `claimed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.