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:
| Table | One row is |
|---|---|
category | one kind of product |
product | one product |
customer | one customer |
orders | one order |
order_item | one 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_id | customer_name | customer_city | ordered |
|---|---|---|---|
| 1 | Somchai Jaidee | Bangkok | 2026-09-02 |
| 3 | Somchai Jaidee | Bangkok | 2026-09-12 |
| 10 | Somchai Jaidee | Bangkok | 2026-10-28 |
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 |
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:
- Insert: a new customer who hasn't ordered yet has no row to be written in.
- Delete: delete Pim's last order and her name, city and phone are gone with it.
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:
- 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 withLIKE. The shop puts each product of an order in its own row oforder_item. - Second normal form (2NF): every column depends on the whole key.
order_item's key is two columns,(order_id, product_id).qtyneeds both (how many of this product in this order). A product's name would need onlyproduct_id, so it belongs inproduct, not inorder_item. - 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 incustomer.
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;| name | orders |
|---|---|
| Somchai Jaidee | 3 |
| Anan Wongsa | 2 |
| Kanya Boonmee | 2 |
| Malee Srisuk | 2 |
| Pim Chaiya | 2 |
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;| name | qty |
|---|---|
| Cheesecake | 2 |
| Coffee | 2 |
| Croissant | 4 |
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;| id | ordered | qty |
|---|---|---|
| 1 | 2026-09-02 | 2 |
| 3 | 2026-09-12 | 1 |
| 7 | 2026-10-10 | 1 |
| 9 | 2026-10-22 | 2 |
| 12 | 2026-11-05 | 1 |
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;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;| paid | at_todays_prices |
|---|---|
| 180.0 | 190.0 |
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:
- Small letters and
_between words:order_item,customer_id. No spaces, so no quotes are ever needed. - Each table's key is
id; a column that points at another table is that table's name plus_id. - The same thing has the same name everywhere: not
cust_idin one table andcustomer_idin another. - Keep away from SQL's own words. The shop's orders table is
ordersbecauseORDERis a word of SQL (ORDER BY);orderwould need quotes in every statement.
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.2 | 0.1 + 0.2 = 0.3 | 0.1 + 0.2 - 0.3 |
|---|---|---|
| 0.3 | 0 | 5.55111512312578e-17 |
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 + 20 | 10 + 20 = 30 | baht |
|---|---|---|
| 30 | 1 | 55.50 |
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.
- List every customer with the number of orders they have, those with none too (they show 0).
- 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 tableproduct_supplier, link Coffee (1) to two suppliers, and list Coffee's suppliers. - 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;| name | orders |
|---|---|
| Somchai Jaidee | 3 |
| Malee Srisuk | 2 |
| Anan Wongsa | 2 |
| Pim Chaiya | 2 |
| Narin Thongdee | 1 |
| Kanya Boonmee | 2 |
| Wichai Saelim | 2 |
| Siriporn Kaewdee | 1 |
| Tawan Rungruang | 0 |
| Lalita Meesuk | 0 |
| name |
|---|
| Doi Farm |
| River Beans |
| name | satang |
|---|---|
| Coffee | 6000 |
| Green Tea | 4500 |
| Orange Juice | 4000 |
| Croissant | 3500 |
| Banana Bread | 6000 |
| Cheesecake | 12000 |
| Potato Chips | 2500 |
| Dried Mango | 9000 |
| Cashew Nuts | 15000 |
| Notebook | 3000 |
| Pen | 1500 |
| Highlighter | 2500 |
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