compare and set

An update that changes a row only if it still holds the value the program expects, and reports whether it did.

In more detail

UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1 either succeeds for one row or affects zero rows, which tells the application the value changed or ran out. Treat zero affected rows as a conflict to report or retry, not as success.

Example

UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1;

Related terms

Taught in

References