Claim a Job From the Queue

job is a queue table. Worker w1 wants work.

Claim the two highest-priority jobs that are still queued: set their state to 'running' and their claimed_by to 'w1'. Highest priority first; where two jobs share a priority, the one queued earlier wins.

Then return the whole table:

SELECT id, priority, state, claimed_by FROM job ORDER BY id;

The constraint that makes this interesting. Several workers run this at the same time. No job may ever be claimed by two of them, and a worker must not wait for another worker's job — if the obvious rows are taken, it should claim the next ones and get on with it.

Expected output


id | priority | state   | claimed_by
---+----------+---------+-----------
1  | 10       | running | w9
2  | 9        | running | w1
3  | 5        | queued  | NULL
4  | 1        | queued  | NULL
5  | 9        | running | w1
6  | 10       | done    | w9
PostgreSQL

Press Run to start the SQL engine.

SensAI
Beta
Tap the mic to stop voice mode