Full answer
sql
CREATE TABLE stock (warehouse_id INTEGER, product_id INTEGER, on_hand INTEGER NOT NULL CHECK (on_hand >= 0), PRIMARY KEY (warehouse_id, product_id));
INSERT INTO stock VALUES (1, 10, 5);
UPDATE stock SET on_hand = on_hand - 3 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 3;
UPDATE stock SET on_hand = on_hand - 4 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 4;
SELECT on_hand, changes() AS rows_changed_by_last FROM stock;| on_hand | rows_changed_by_last |
|---|---|
| 2 | 0 |
The second reservation asked for more than remained, so the conditional UPDATE changed no rows (changes() is 0) and the application can report "out of stock". The CHECK is a second line of defence if some code path forgets the condition.
A movements ledger (stock_moves(id, warehouse_id, product_id, delta, reason, created_at)) written in the same transaction gives an audit trail and lets you rebuild balances. Reservations for carts can be a separate reserved column or table with expiry, so "available = on_hand - reserved".
sql
CREATE TABLE stock (warehouse_id INTEGER, product_id INTEGER, on_hand INTEGER NOT NULL CHECK (on_hand >= 0), PRIMARY KEY (warehouse_id, product_id));
INSERT INTO stock VALUES (1, 10, 5);
UPDATE stock SET on_hand = on_hand - 3 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 3;
UPDATE stock SET on_hand = on_hand - 4 WHERE warehouse_id = 1 AND product_id = 10 AND on_hand >= 4;
SELECT on_hand, changes() AS rows_changed_by_last FROM stock;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Stock per (warehouse, product) with CHECK on_hand >= 0
- Conditional atomic UPDATEs prevent overselling
- A movements ledger explains every change
- Reservations reduce available stock separately
Common mistakes
- Read-then-write stock updates in application code
- Balances without an audit trail
Follow-ups
- How would you allocate an order across warehouses?
- How would cart reservations expire?
Tips
- Show the zero-rows-changed case