Reproduce a lost update and protect the write
Observe a read-then-write race at `READ COMMITTED` and compare it with an atomic update and an optimistic concurrency check.
What you are trying to do
Use a SQL Server sandbox, two sessions, and one instructor-seeded row in a disposable dbo.LabCounter table. Reset its counter to zero between trials. This lab modifies that lab row, so its SQL field is empty.
Work through it
- In both sessions, set
READ COMMITTED, begin a transaction, read the counter into a session-local variable, and pause before writing. Confirm both sessions read the same starting value. - Have Session A write
@ObservedValue + 1and commit. Then let Session B write its stale@ObservedValue + 1and commit. Read the final value. It is one increment even though two workers completed. - Reset the row. In both sessions, execute a single statement that sets the value to
Value + 1. The second writer works from the current row value after obtaining its update lock. - Reset again and try optimistic concurrency. Update with both the key and original value in the WHERE clause. Check
@@ROWCOUNT. A zero row count means another writer changed the row first. - Compare the results and explain which invariant each method protects. Do not enable snapshot isolation or change database options in this drill.
- Review Microsoft's locking and row-versioning guide and the isolation-level reference. Locking and row versioning · Isolation levels
Check your work
The stale read-then-write trial finishes with one instead of two increments. Two atomic increments finish at two. The optimistic trial detects a stale value through a zero-row update and requires the application to retry or report a conflict.
Knowledge check
Commands in this lesson
Next lesson Claim work safely from a shared queue