Skip to content

Designing tables: normal forms in plain words

Working knowledgeConcept

A table that copies a fact into many rows works fine until that fact changes, and then it gives two answers to one question. Normal forms come down to one rule, one fact in one place, and it is worth knowing when to break it.

01 A bookings table that looks fine

A small hotel starts with one table, the way it would in a spreadsheet: one row per booking, with everything you might want to show on the booking page.

flat.sql
CREATE TABLE bookings_flat (
id int PRIMARY KEY,
guest_email text,
guest_name text,
room int,
room_type text,
price int,
check_in date
);
INSERT INTO bookings_flat VALUES
(1, 'ana@x.com', 'Ana Silva', 101, 'single', 80, '2024-03-01'),
(2, 'ben@y.com', 'Ben Ito', 102, 'double', 120, '2024-03-01'),
(3, 'ana@x.com', 'Ana Silva', 201, 'double', 120, '2024-03-05'),
(4, 'cy@z.com', 'Cy Park', 101, 'single', 80, '2024-03-07'),
(5, 'ana@x.com', 'Ana Silva', 102, 'double', 120, '2024-03-09');

It works, and every query is a simple SELECT. But look at what the rows actually say. Some cells are not about the booking at all: they repeat a fact about something else.

Which cells repeat a fact that lives somewhere else
bookings_flat · 5 rows
guest_emailguest_nameroomroom_typeprice
1ana@x.comAna Silva101single80
2ben@y.comBen Ito102double120
3ana@x.comAna Silva201double120
4cy@z.comCy Park101single80
5ana@x.comAna Silva102double120
  • Ana’s email and name ×3
  • “a double costs 120” ×3
  • “a single costs 80” ×2

Ana’s name is a fact about Ana, not about booking 3. The price is a fact about the room type, not about room 102. Each is written down once per booking.

02 What goes wrong when a fact is copied

A copy is harmless until the fact changes. Then every copy has to change together, and the database has no idea they are meant to.

One guest renamed, three copies of her name
Step 1 of 5
bookings_flat (booking id × column)
guest_emailguest_nameroomroom_typeprice
1ana@x.comAna Silva101single80
2ben@y.comBen Ito102double120
3ana@x.comAna Silva201double120
4cy@z.comCy Park101single80
5ana@x.comAna Silva102double120
SELECT DISTINCT guest_name WHERE guest_email = ana@x.com
Empty
  • a copy of the same fact
  • just updated
  • being read
  • contradicts another copy

Ana tells the hotel her surname is now Sousa. Her name is stored three times, once in each of her bookings: 1, 3 and 5.

3 copies of the name

That is a real run on Postgres 16. The same table fails in two more ways, and together they are the classic anomalies:

The three anomalies, in bookings_flat
AnomalyWhat you tryWhat happens
UpdateRename Ana, or raise the price of a doubleYou must find and change every copy. Miss one and the table contradicts itself.
InsertAdd room 301, a suite, before anyone books itThere is no row to put it in without inventing a booking with empty guest columns.
DeleteCancel booking 4, Cy’s only bookingCy’s email and name vanish with it. Had it been the last booking of a single, the fact that singles cost 80 would have gone too.
SQL
DELETE FROM bookings_flat WHERE id = 4;
SELECT count(*) FROM bookings_flat WHERE guest_email = 'cy@z.com';
count
-------
0

03 The rule: every fact depends on the key

Normalisation is one idea: each fact is stored in one place, in the table whose key it describes. A table’s key names one thing, such as one booking or one guest. Every other column should be a fact about that thing, and nothing else. The textbook normal forms are that idea applied in three passes.

The first three normal forms, in plain words
FormPlain ruleBreaks it hereFix
1NFOne value per cell, no repeating columns`nights = 'Mar 1, Mar 2'` in one cell, or `phone1`, `phone2`, `phone3`A row per value, in its own table
2NFWith a key of several columns, every other column needs the whole keyA `booking_nights (booking_id, night)` table that also holds `guest_name`, which depends on `booking_id` aloneMove the column to the table keyed by `booking_id`
3NFNo column depends on another non-key column`price` depends on `room_type`, and `room_type` on `room`; neither is about the bookingA table keyed by what the fact is about: `room_types`, `rooms`

A quick test for any column: finish the sentence “given the key, there is exactly one…”. Given booking 3, there is exactly one check-in date: it belongs. Given booking 3 there is one guest name too, but only because there is one guest; the name is really fixed by the guest, so it belongs with the guest. There are stricter forms (BCNF, 4NF, 5NF), but a design that passes 3NF with this test is where almost all practical tables stop.

04 Split it: one table per kind of thing

Each repeated fact becomes a row in a table of its own, and the booking refers to it by key. Foreign keys (REFERENCES) make the database check that every reference points at a row that exists.

normalised.sql
CREATE TABLE guests (
id int PRIMARY KEY,
email text NOT NULL UNIQUE,
name text NOT NULL
);
CREATE TABLE room_types (
type text PRIMARY KEY,
price int NOT NULL
);
CREATE TABLE rooms (
room_no int PRIMARY KEY,
type text NOT NULL REFERENCES room_types
);
The same five bookings, split by what each fact is about
guests
emailname
1ana@x.comAna Silva
2ben@y.comBen Ito
3cy@z.comCy Park
room_types
price
single80
double120
rooms
type
101single
102double
201double
bookings
guest_idroom_nocheck_in
1110103-01
2210203-01
3120103-05
4310103-07
5110203-09

Each name, each price and each room’s type now appears exactly once. The bookings table holds only what is about a booking: who, which room, when.

Renaming Ana is now one UPDATE guests ... WHERE id = 1, and there is no second copy to miss. A suite can exist before its first booking. Cancelling Cy’s booking leaves Cy in guests. The booking page still gets its flat view, built by joins when you read:

booking-page.sql
SELECT b.id, g.email, g.name, r.room_no, r.type, t.price, b.check_in
FROM bookings b
JOIN guests g ON g.id = b.guest_id
JOIN rooms r ON r.room_no = b.room_no
JOIN room_types t ON t.type = r.type
ORDER BY b.id;
id | email | name | room_no | type | price | check_in
----+-----------+-----------+---------+--------+-------+------------
1 | ana@x.com | Ana Silva | 101 | single | 80 | 2024-03-01
2 | ben@y.com | Ben Ito | 102 | double | 120 | 2024-03-01
3 | ana@x.com | Ana Silva | 201 | double | 120 | 2024-03-05
4 | cy@z.com | Cy Park | 101 | single | 80 | 2024-03-07
5 | ana@x.com | Ana Silva | 102 | double | 120 | 2024-03-09
(5 rows)
Flat tableCheap reads, risky writesEvery fact is right there, but every change must find all its copies.
NormalisedOne write per factA change touches one row. Reads join a few tables, which is what indexes on the keys are for.

05 Let the database keep it true

Splitting the tables only helps if the links between them cannot break. The constraints in normalised.sql turn mistakes into errors at write time, which is much cheaper than finding them in a report later. Real Postgres 16 errors:

SQL
DELETE FROM guests WHERE id = 3;
-- ERROR: update or delete on table "guests" violates foreign key
-- constraint "bookings_guest_id_fkey" on table "bookings"
-- DETAIL: Key (id)=(3) is still referenced from table "bookings".
INSERT INTO bookings VALUES (6, 9, 101, '2024-03-12');
-- ERROR: insert or update on table "bookings" violates foreign key
-- constraint "bookings_guest_id_fkey"
-- DETAIL: Key (guest_id)=(9) is not present in table "guests".
INSERT INTO guests VALUES (4, 'ana@x.com', 'Ana S');
-- ERROR: duplicate key value violates unique constraint "guests_email_key"
-- DETAIL: Key (email)=(ana@x.com) already exists.

Notice that guests is keyed by a plain id, with email as UNIQUE. Email identifies a guest today, but people change it. If email were the primary key, a change would have to rewrite every booking that points at it. A key that never changes, plus a unique constraint on the natural identifier, gives you both.

06 When to break the rule

Copying a fact on purpose is called denormalising. It is a trade, not a sin, as long as you know which copy is the truth and who keeps the others in step. Before you do it, check that it is really a copy. The price a guest paid is not the same fact as today’s price for that room type:

SQL
ALTER TABLE bookings ADD COLUMN price_per_night int;
-- fill it from room_types when each booking is made
UPDATE room_types SET price = 95 WHERE type = 'single';
SELECT b.id, b.room_no, b.price_per_night AS paid, t.price AS today
FROM bookings b
JOIN rooms r USING (room_no)
JOIN room_types t USING (type)
WHERE r.type = 'single'
ORDER BY b.id;
id | room_no | paid | today
----+---------+------+-------
1 | 101 | 80 | 95
4 | 101 | 80 | 95

The price went up, and old bookings must keep what was agreed. price_per_night is a fact about the booking, frozen at the moment it was made, so storing it is normalised. Order lines with unit_price, invoices with an address: the same idea. Real denormalisation is when the copy is meant to stay equal to the original:

Counters and totalsKept in the same transactionA seller’s review_count or an order’s total, updated in the same transaction as the rows it counts (or by a trigger), so a page does not count thousands of rows on every view.
Read modelsRebuilt from the truthA reporting table, a materialised view or a search index, filled from the normalised tables and allowed to lag. If it goes wrong, you rebuild it.
Copy with no ownerDriftsA column copied “to save a join”, which some code paths update and others forget. This is the bookings_flat problem again.

Start normalised and denormalise only when a measured query needs it. Going the other way, from copies that have already drifted back to one truth, means deciding which of the conflicting values was right, often by hand.

07 When it bites

tags = 'wifi,sea-view,balcony'A list in one cellYou cannot index, join or constrain the parts, and LIKE '%sea%' finds the wrong things. Use a room_tags (room_no, tag) table. Postgres arrays are fine for a short list you only ever read whole.
phone1, phone2, phone3Numbered columnsA guest with four phones does not fit, and “find this number” checks three columns. Put phones in their own table, one row each.
entity, attribute, valueOne table for everythingStoring every field as a generic key-value row throws away types, NOT NULL and foreign keys, and every read becomes a pile of self-joins. Use real columns, or a jsonb column for the truly free-form part.
age intStoring what you can computeAn age is out of date a year later. Store birth_date and compute the age when you read it. The same goes for totals you can sum cheaply.
countries, regions, cities, streetsSplitting too farAn address used only as a label on a booking is one fact to that booking. Splitting it into four tables adds joins and protects nothing, because nobody updates “the street” for everyone at once.

08 Check yourself

Question

In bookings_flat, raising the price of a double room means updating how many rows?

Question

An order_lines table stores unit_price for each product ordered, even though products also has a price. Is that a harmful duplicate?

Question

Why key guests by an id and make email merely UNIQUE?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?