The Goal
Build the heart of an ordering system: placing an order must (1) check stock, (2) create the order and its line, (3) reduce stock, all in one transaction, and (4) record price changes automatically. If anything fails, nothing is saved.
Step 1: Tables
sql
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(30) NOT NULL);
CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(30) NOT NULL, price DECIMAL(10,2) NOT NULL, stock INT NOT NULL CHECK (stock >= 0));
CREATE TABLE orders (id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, product_id INT NOT NULL, qty INT NOT NULL, order_date DATE NOT NULL, FOREIGN KEY (customer_id) REFERENCES customers(id), FOREIGN KEY (product_id) REFERENCES products(id));
CREATE TABLE price_history (id INT AUTO_INCREMENT PRIMARY KEY, product_id INT NOT NULL, old_price DECIMAL(10,2), new_price DECIMAL(10,2), changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
CREATE VIEW v_order_lines AS SELECT o.id AS order_id, c.name AS customer, p.name AS product, o.qty, o.qty * p.price AS line_total, o.order_date FROM orders o JOIN customers c ON c.id = o.customer_id JOIN products p ON p.id = o.product_id;
Step 2: The Procedure
sql
CREATE PROCEDURE place_order(IN p_customer INT, IN p_product INT, IN p_qty INT)
BEGIN
DECLARE v_stock INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
IF p_qty <= 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Quantity must be positive';
END IF;
START TRANSACTION;
SELECT stock INTO v_stock FROM products WHERE id = p_product FOR UPDATE;
IF v_stock IS NULL THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Unknown product';
END IF;
IF v_stock < p_qty THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Not enough stock';
END IF;
INSERT INTO orders (customer_id, product_id, qty, order_date) VALUES (p_customer, p_product, p_qty, '2025-07-01');
UPDATE products SET stock = stock - p_qty WHERE id = p_product;
COMMIT;
END;
How it works: SELECT ... FOR UPDATE locks the product row, so two buyers cannot both take the last item. SIGNAL raises a clear error, and the EXIT HANDLER rolls everything back and passes the error on with RESIGNAL.
Step 3: Place Good and Bad Orders
sql
CALL place_order(1, 2, 3);
CALL place_order(2, 1, 1);
SELECT order_id, customer, product, qty FROM v_order_lines ORDER BY order_id;
Result:
| order_id | customer | product | qty |
| 1 | Asha | Headset | 3 |
| 2 | Ben | Notebook | 1 |
sql
SELECT id, name, stock FROM products ORDER BY id;
Result:
| id | name | stock |
| 1 | Notebook | 49 |
| 2 | Headset | 2 |
| 3 | Gadget | 2 |
Step 4: Failure Cases
sql
CALL place_order(1, 3, 99);
Not enough stock
ERROR 1644: Not enough stock
sql
CALL place_order(1, 42, 1);
Unknown product
ERROR 1644: Unknown product
sql
CALL place_order(1, 1, 0);
Quantity must be positive
ERROR 1644: Quantity must be positive
Now prove that failed calls left no trace. This is the real output of one connection that made one good call and then the three bad ones, followed by a check of the data:
text
CALL place_order(1, 2, 3) -> OK
CALL place_order(1, 3, 99) -> ERROR 1644 Not enough stock
CALL place_order(1, 42, 1) -> ERROR 1644 Unknown product
CALL place_order(1, 1, 0) -> ERROR 1644 Quantity must be positive
SELECT (SELECT COUNT(*) FROM orders) AS orders,
(SELECT stock FROM products WHERE id = 3) AS gadget_stock,
(SELECT stock FROM products WHERE id = 2) AS headset_stock;
-> orders = 1, gadget_stock = 2, headset_stock = 2
Only the good order exists: one order row, the headset stock went from 5 to 2, and the gadget stock is unchanged.
Step 5: Price History Trigger
sql
CREATE TRIGGER trg_products_price AFTER UPDATE ON products FOR EACH ROW
BEGIN
IF OLD.price <> NEW.price THEN
INSERT INTO price_history (product_id, old_price, new_price) VALUES (OLD.id, OLD.price, NEW.price);
END IF;
END;
sql
UPDATE products SET price = 12.00 WHERE id = 1;
UPDATE products SET price = 12.00 WHERE id = 1;
UPDATE products SET price = 55.00 WHERE id = 3;
SELECT product_id, old_price, new_price FROM price_history ORDER BY id;
Result:
| product_id | old_price | new_price |
| 1 | 10.00 | 12.00 |
| 3 | 50.00 | 55.00 |
The second update did not change the price, so no history row was written.
Step 6: Daily Summary View
sql
SELECT order_date, COUNT(*) AS orders, SUM(qty) AS units, SUM(line_total) AS revenue FROM v_order_lines GROUP BY order_date ORDER BY order_date;
Result:
| order_date | orders | units | revenue |
| 2025-07-01 | 3 | 6 | 150.00 |
Step 7: Think About Concurrency
- Two sessions buying the last unit:
FOR UPDATE makes the second wait, then it sees stock 0 and fails cleanly.
- A deadlock is still possible if a future procedure locks several products in different orders. Lock products in id order.
- The application should retry on error 1213 and show a friendly message for the
45000 errors.
Extra Challenges
- Add a
cancel_order(order_id) procedure that returns the stock.
- Support several products in one order using a temporary table or JSON parameter.
- Add a trigger that blocks negative stock directly.
- Write a
CALL script in Python that retries on deadlock.
Conclusion
You combined a stored procedure, FOR UPDATE, SIGNAL, an exit handler with ROLLBACK and RESIGNAL, a trigger for history and a view for reporting. Failed orders leave no partial data.
Quick Summary: stored procedure, transaction, FOR UPDATE, SIGNAL, RESIGNAL, trigger, view.