Two people, one seat
Two people tap seat 14A at once. How does exactly one win?
The lesson
- Never check first and change after.
- Put the check inside the change,
- then count the rows.
The code
the table one row for each seat
UPDATE show_seat
the change mark it held, by Priya
SET status = 'held', held_by = 'Priya'
which row only the row of seat 14A
WHERE seat_id = '14A'
the check and only if it is still free
AND status = 'available';
- 1 row changed
- the seat is yours
- 0 rows changed
- someone else got it first
What this lab leaves out
- Why the second query waits. The database runs two changes to one row one after the other. Rahul's query waits for Priya's, then checks the row as it is now. It says held, so his query changes nothing.
- Checking first is not always wrong. A check that locks the row first also gives one winner: the second request waits before it can even try. The video calls that the pessimistic style, and this lab's one query the optimistic style. What breaks is a check with nothing protecting it.
- The video's row has more on it. There is one row for each seat of each show, and the row points to a hold record. The hold record carries the person and the time the hold ends. Here the row just names who holds the seat, so it can be read at a glance.
In the video
This idea is taught at 14:01 in the video, with the rest of the design around it.