← Learning Hub
Advanced

Transactions and Good Table Design

When money moves from one account to another, both changes must happen, or neither. Transactions guarantee this. Good table design (normalisation) avoids repeating data, so information stays consistent and easy to update.

Transactions: all or nothing

A transaction groups changes so they all happen, or none do. Placing an order must reduce stock and create the order - never just one of them.

Example
BEGIN;
INSERT INTO orders VALUES (109, 3, '2026-11-26', 'placed');
INSERT INTO order_items VALUES (109, 2, 1, 1299);
UPDATE products SET stock = stock - 1 WHERE id = 2;
COMMIT;

SELECT name, stock FROM products WHERE id = 2;

-- Result:
-- name        | stock
-- ------------+------
-- Denim Jeans | 59
▶ Try it yourself

If something fails in the middle, ROLLBACK undoes everything since BEGIN.

  • Atomic - all or nothing
  • Consistent - rules (constraints) always hold
  • Isolated - running transactions don't see each other's half-done work
  • Durable - once committed, it survives a crash

Normalisation: don't repeat data

Store each fact in one place. If every order row repeated the customer's name and city, changing a city would mean updating many rows - and missing one makes the data wrong. So we keep customers in their own table and store only customer_id in orders.

  • 1NF - one value per cell (no "Pen, Book" lists in one column)
  • 2NF - every column depends on the whole key
  • 3NF - no column depends on another non-key column (city belongs to the customer, not the order)
Notice that order_items stores the price paid. That is a deliberate copy: product prices change later, but an old order must keep the price the customer actually paid.
Key points
  • BEGIN ... COMMIT makes changes all-or-nothing; ROLLBACK undoes them.
  • Normalise: store each fact once and link with keys.
  • Design tables around how the data will be used.

📝 Test yourself

1. What does ROLLBACK do?
2. Why is the customer's city not stored in the orders table?
3. Fill in the statement that saves a transaction:
BEGIN; ... ; ;