SQL Flow Field Guide

Claim work safely from a shared queue

Use one atomic update with locking hints and OUTPUT to claim one ordered queue row per worker.

What you are trying to do

Use SQL Server in a dedicated scratch database with READ_COMMITTED_SNAPSHOT off for this lab, a shared instructor-seeded queue table, and two worker sessions. The shared table and concurrent timing make a pasted script unsafe, so sql is empty.

Work through it

  1. Confirm the queue has at least two ready rows and a stable order key such as EnqueuedAt, JobId. Record the database's READ_COMMITTED_SNAPSHOT setting without changing it.
  2. In each worker session, run the same single-statement pattern: a CTE selects TOP (1) ready row with UPDLOCK, READPAST, ROWLOCK, ordered by the queue keys. An UPDATE changes that row to claimed and uses OUTPUT inserted.JobId to return the claim.
  3. Start both workers close together. Compare returned IDs and the persisted queue state. Each worker must claim a different row when two are available.
  4. Repeat with an empty queue and verify that OUTPUT returns no row. Check how cancellation and transaction rollback affect a claim before designing a real worker.
  5. Treat ROWLOCK as a request, not a guarantee. If the database uses row versioning, validate the documented READPAST restrictions and required locking hint for that configuration.
  6. Use Microsoft's table-hint reference for the supported combinations and restrictions. Table hints

Check your work

The two-session run returns distinct job IDs when two rows are ready, and each returned row is marked claimed. The empty-queue run returns no claim. The learner names the isolation and database option assumptions used by the test.

Knowledge check

Commands in this lesson

Next lesson Recover a failed transaction safely