24. Designing tables well

One thing per table, one fact in one place: how the shop's tables were drawn, and why.

One thing per table

The shop could have kept everything in one big sheet: each line an order, with the customer's name, city and phone, and the products, all side by side. It would look simple on the first day. The shop instead has five tables, each about one kind of thing:

TableOne row is
categoryone kind of product
productone product
customerone customer
ordersone order
order_itemone product in one order

The rows point at each other through id numbers (chapter 22). A good test for a table: can you say in one short sentence what one row is? "One customer" is good. "An order, with the customer, and some of the products" is a sign that several things are squeezed into one table.

One fact in one place

The reason is a rule worth remembering: every fact is written down once. Somchai's city is in one row of customer, and nowhere else. Let's see what goes wrong when it is copied. Here is a table that keeps the customer's name and city in every order:

CREATE TABLE order_flat (
  order_id      INTEGER PRIMARY KEY,
  customer_name TEXT,
  customer_city TEXT,
  ordered       TEXT
);
INSERT INTO order_flat
  SELECT o.id, c.name, c.city, o.ordered
  FROM orders AS o JOIN customer AS c ON c.id = o.customer_id;
SELECT * FROM order_flat WHERE customer_name = 'Somchai Jaidee';
order_idcustomer_namecustomer_cityordered
1Somchai JaideeBangkok2026-09-02
3Somchai JaideeBangkok2026-09-12
10Somchai JaideeBangkok2026-10-28
3 rows

Somchai's city is now written three times. He moves to Chiang Mai, and the person at the counter fixes only the order in front of them:

UPDATE order_flat SET customer_city = 'Chiang Mai' WHERE order_id = 10;
SELECT DISTINCT customer_city FROM order_flat
WHERE customer_name = 'Somchai Jaidee';
customer_city
Bangkok
Chiang Mai
2 rows

Where does Somchai live? The table now says two things, and nothing tells which is true. That is an update anomaly. Copying causes two more:

In the shop's design none of this happens: the move is one UPDATE customer ... WHERE id = 1, every order sees it at once through a JOIN, a customer exists without orders, and deleting an order never deletes a customer.

Normal forms in plain words

Database people describe good tables with normal forms (normalization). The first three are enough for nearly every program, and each is one plain rule:

  1. First normal form (1NF): one value in each cell. No lists in a column ("Coffee x2, Croissant x2"), and no repeated columns (product1, product2, product3). A list in one cell can't be joined, counted or checked; "which orders have coffee" becomes a guess with LIKE. The shop puts each product of an order in its own row of order_item.
  2. Second normal form (2NF): every column depends on the whole key. order_item's key is two columns, (order_id, product_id). qty needs both (how many of this product in this order). A product's name would need only product_id, so it belongs in product, not in order_item.
  3. Third normal form (3NF): no column depends on another column that isn't the key. In order_flat, the city depends on the customer, not on the order. That is why it went wrong. The city belongs in customer.

People sum it up as: every column says something about the key, the whole key, and nothing but the key.

One-to-many and many-to-many

Ties between tables come in two shapes.

One-to-many: one customer has many orders; each order has one customer. The foreign key goes on the "many" side: orders.customer_id. Count each customer's orders:

SELECT c.name, COUNT(o.id) AS orders
FROM customer AS c LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY orders DESC, c.name
LIMIT 5;
nameorders
Somchai Jaidee3
Anan Wongsa2
Kanya Boonmee2
Malee Srisuk2
Pim Chaiya2
5 rows

Many-to-many: one order has many products, and one product is in many orders. Neither side can hold a single foreign key, so a linking table sits between them, with one row for each pair. That is order_item: a foreign key to each side, and the pair as its primary key, so a product appears in an order only once. From the order's side, what's in order 9:

SELECT p.name, i.qty
FROM order_item AS i JOIN product AS p ON p.id = i.product_id
WHERE i.order_id = 9
ORDER BY p.name;
nameqty
Cheesecake2
Coffee2
Croissant4
3 rows

And from the product's side, which orders have Coffee (product 1):

SELECT o.id, o.ordered, i.qty
FROM order_item AS i JOIN orders AS o ON o.id = i.order_id
WHERE i.product_id = 1
ORDER BY o.id;
idorderedqty
12026-09-022
32026-09-121
72026-10-101
92026-10-222
122026-11-051
5 rows

A linking table can also hold facts that belong to the pair: how many (qty), and at what price.

Why order_item keeps its own price

Wait: product has a price, and order_item has a price too. Isn't that a fact in two places? It isn't, because they are two different facts: product.price is the price today; order_item.price is the price the customer actually paid on that day. Raise the price of Coffee to 60:

UPDATE product SET price = 60 WHERE id = 1;
✓ 1 row changed

Order 1 (two coffees and two croissants) was paid at the old price. Compare its total from order_item with what it would be from today's prices:

SELECT SUM(i.qty * i.price) AS paid,
       SUM(i.qty * p.price) AS at_todays_prices
FROM order_item AS i JOIN product AS p ON p.id = i.product_id
WHERE i.order_id = 1;
paidat_todays_prices
180.0190.0
1 row

The order still says 180, what was really paid. Had the shop worked out old orders from product.price, every receipt would change each time a price changed.

Copying on purpose is fine when the copy is a fact of its own moment: the price at the sale, the address printed on an invoice (a tax invoice must keep showing the address it was issued to), a monthly report kept as it was. The test: when the original changes, should the copy change too? If yes, don't copy; use a JOIN. If no, the copy is a different fact and belongs where it is.

Names, and money

Names. Choose them once and keep to them, the whole database through:

Money. The shop keeps prices in REAL, which is fine for learning, but a REAL is a binary fraction and can't hold most decimals exactly:

SELECT 0.1 + 0.2, 0.1 + 0.2 = 0.3, 0.1 + 0.2 - 0.3;
0.1 + 0.20.1 + 0.2 = 0.30.1 + 0.2 - 0.3
0.305.55111512312578e-17
1 row

The sum is shown as 0.3, because a result is rounded for showing, yet the test says 0 (false): the sum is a hair above 0.3, and taking 0.3 away leaves 0.0000000000000000555 (5.55111512312578e-17), not 0. On one receipt nobody notices; across a year of sales the hairs add up, and a check like "does this payment equal the bill" fails. The safe way is to keep money as whole satang in an INTEGER: 55.50 baht is 5550. Whole numbers add up exactly:

SELECT 10 + 20, 10 + 20 = 30, printf('%.2f', 5550 / 100.0) AS baht;
10 + 2010 + 20 = 30baht
30155.50
1 row

Divide by 100 only when you show the amount to people. (Chapter 7's round() helps when you must work with REAL; whole satang is better still.)

Changing a working table's design later means rebuilding it (chapter 23) and changing every program that uses it. Ten minutes with paper before CREATE TABLE saves days afterwards: write each table's "one row is ...", its key, and its links.

  1. List every customer with the number of orders they have, those with none too (they show 0).
  2. The shop buys from suppliers. One supplier sells many products, and one product can come from several suppliers. Make supplier (id, name) and the linking table product_supplier, link Coffee (1) to two suppliers, and list Coffee's suppliers.
  3. Show each product's name and its price in whole satang, as an INTEGER.
Show the answer
SELECT c.name, COUNT(o.id) AS orders
FROM customer AS c LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY c.id;

CREATE TABLE supplier (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE product_supplier (
  product_id  INTEGER NOT NULL REFERENCES product(id),
  supplier_id INTEGER NOT NULL REFERENCES supplier(id),
  PRIMARY KEY (product_id, supplier_id)
);
INSERT INTO supplier VALUES (1, 'Doi Farm'), (2, 'River Beans');
INSERT INTO product_supplier VALUES (1, 1), (1, 2);
SELECT s.name
FROM product_supplier AS ps JOIN supplier AS s ON s.id = ps.supplier_id
WHERE ps.product_id = 1
ORDER BY s.name;

SELECT name, CAST(round(price * 100) AS INTEGER) AS satang FROM product;
nameorders
Somchai Jaidee3
Malee Srisuk2
Anan Wongsa2
Pim Chaiya2
Narin Thongdee1
Kanya Boonmee2
Wichai Saelim2
Siriporn Kaewdee1
Tawan Rungruang0
Lalita Meesuk0
10 rows
name
Doi Farm
River Beans
2 rows
namesatang
Coffee6000
Green Tea4500
Orange Juice4000
Croissant3500
Banana Bread6000
Cheesecake12000
Potato Chips2500
Dried Mango9000
Cashew Nuts15000
Notebook3000
Pen1500
Highlighter2500
12 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made