Learning navigation

Code with Animation

Normalization

Store each fact once, with three normal forms in plain words, and see the update, insertion and deletion problems it prevents.

SQL7 min readConcept 37 of 44

Each fact in one place

Normalization is a way of designing tables so that each fact is stored once, in the table where it belongs. It was introduced by Edgar Codd in 1970, with the aim of removing problems when rows are inserted, updated and deleted.

It is done in steps called normal forms. The first three are the ones you will use every day: 1NF, 2NF and 3NF.

Stored twice means wrong once

If Asha's city is written in every one of her orders, then moving house means finding and changing every row. Miss one, and the database now disagrees with itself. Storing a fact once removes that risk.

The three forms, in plain words

1NF: one value per field. A field holds a single value, not a list such as 'Pen, Ruler'. Give each item its own row.

2NF: the whole key. When a row is identified by two columns together, every other column must depend on both, not on just one of them. A product's name belongs in a products table, not in every order line.

3NF: nothing but the key. A column must depend on the key, not on another non-key column. If an order stores customer and also the customer's city, the city depends on the customer, not on the order, so it moves to a customers table.

The example splits one wide table, orders_flat, into customers and orders. The orders point at the customer, and each city is stored once.

Break the wide table, then the split one

With One wide table, try each change and watch what goes wrong. Then switch to Split into two tables and try the same three.

CREATE TABLE orders_flat (
order_id integer PRIMARY KEY,
customer text, city text, item text
);
orders_flat (3 rows)
order_idintegercustomertextcitytextitemtext
101AshaPuneNotebook
102AshaPunePen
103BenLeedsRuler

One table holds the order and everything about the customer. Asha's city appears twice, once for each of her orders.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1A table stores each order with the customer's city. A customer with 2 orders moves to Rome, and only one order row is updated. What is this problem called?
  2. 2A field holds the text 'Pen, Ruler, Tape'. Which normal form does that break?
  3. 3An orders table stores `customer` and `city`, and city depends on the customer. Which step fixes it?

Remember this

  • Normalization means storing each fact once, in the table where it belongs.
  • 1NF: one value per field. 2NF: depend on the whole key. 3NF: depend on nothing but the key.
  • A badly designed table causes update, insertion and deletion anomalies.
  • Normalizing costs joins. Denormalize only on purpose, for speed, after the design is correct.

Done with this concept?

Mark it complete to track your progress. No login needed.