Guarded UPDATE

A guarded UPDATE is a SQL UPDATE whose WHERE clause checks the conditions that must remain true for a change to succeed. In this course, inventory reservations check both the available quantity and the previously observed version, then inspect RowsAffected to determine whether the reservation succeeded.

Minimal example

sql
UPDATE stock
SET on_hand = on_hand - 1,
    version = version + 1
WHERE item_id = 42
  AND restaurant_id = 7
  AND on_hand >= 1
  AND version = 7;

Learn this concept

Lesson 8.1 · Optimistic locking for stock

Used in exercises

Exercise 8.2 · Stock reservation service
Prerequisite conceptsOptimistic lockingdatabase/sql