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.

SqlResilience

Code

sqlsnippet
12 lines
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

FAQ

Which tables does the SQL touch?
The references are `jobs`, `skip`, `claimed`.