Skip to content
Visual explainer 3h to learn 3 steps

Normalisation & when to denormalise

Normalise to 3NF and justify any deliberate denormalisation.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 14 of 30

In short

Normalisation removes duplicated facts so each piece of data lives in one place. That prevents update anomalies, where changing a fact in one row leaves stale copies elsewhere. Denormalise only on purpose, for measured speed.

Explained simply

Normalisation is a set of rules for splitting data into tables so that every fact is stored in exactly one place. If a customer's address is written on 500 orders, a move means 500 updates, and missing one leaves the data saying two different things.

The rules come in levels called normal forms. First normal form (1NF) says one value per cell. Second (2NF) says every column must depend on the whole key. Third (3NF) says columns must not depend on other non-key columns. Most app databases aim for 3NF.

The problems normalisation prevents are called anomalies. An update anomaly is changing a fact in one place but not another. An insert anomaly is being unable to save a fact until some unrelated data exists. A delete anomaly is losing a fact by accident when you delete something else.

Denormalising means copying data on purpose, usually to make reads faster. It is a trade: faster reads, but now you must keep the copies in sync. Do it only after measuring a real problem, and write down how the copies stay correct.

Press Play on a diagram to walk through it one step at a time.

MapThe first three normal forms
Normal forms
  • 1NF
    • Atomic values per cell
    • No repeating groups or lists
  • 2NF
    • Is 1NF
    • Non-key columns depend on the whole key
  • 3NF
    • Is 2NF
    • No column depends on another non-key column
CompareNormalised vs denormalised
Normalised
  • Each fact stored once
  • Updates touch one row
  • More joins to read
  • Default for app data
Denormalised
  • Facts copied for speed
  • Updates must sync copies
  • Fewer joins
  • Reports, caches, analytics
CompareThe three anomalies
Update
  • Same fact on many rows
  • Teacher name on every enrolment
  • Change one, miss others
  • Data disagrees with itself
Insert
  • Fact needs unrelated data
  • New course, no students yet
  • Must invent a fake row
  • Or simply can't save it
Delete
  • Fact lives only with other data
  • Last student leaves
  • Course info vanishes too
  • Lost by accident

In depth

1NF: one value per cell, no repeating groups

A table is in first normal form when each cell holds a single value and there are no repeating columns. Two common breaks: a phones column holding '555-1234, 555-9876', and columns like phone1, phone2, phone3. Both make queries awkward (how do you find who owns 555-9876?) and both put a silent limit on the data.

The fix is a child table: customer_phones(customer_id, phone, kind), one row per phone. Now any number of phones fits, each one can be indexed, and a UNIQUE constraint can stop duplicates.

Postgres arrays and jsonb technically let you store lists in a cell. That is fine for data you always read and write as a whole, such as a list of UI preferences. If you need to search, join, or enforce rules on the items, use rows instead.

  • Lists in a cell: split into a child table
  • Columns named x1, x2, x3: split into rows
  • Arrays and jsonb are fine for blobs you never query by item

2NF and 3NF: depend on the key, the whole key, and nothing but the key

A functional dependency means one column decides another: product_id decides product_name. Normal forms are about checking that these dependencies point at the key.

2NF matters when the key has several columns. In order_items(order_id, product_id, quantity, product_name), quantity depends on both columns, but product_name depends only on product_id. That is a partial dependency, so product_name moves to products.

3NF removes transitive dependencies, where a column depends on another non-key column. In employees(id, name, dept_id, dept_name), dept_name depends on dept_id, not on the employee. Move it to departments.

Boyce-Codd normal form (BCNF) is a slightly stricter 3NF that matters in rare tables with several overlapping candidate keys. For everyday app design, 3NF is the goal.

FlowNormalising one messy orders table
  1. 1
    Raw sheet

    orders with customer, city and a product list

  2. 2
    1NF

    One row per order line; no lists in cells

  3. 3
    2NF

    Product name moves to products (depends on product_id only)

  4. 4
    3NF

    City moves to customers (depends on customer, not order)

  5. 5
    Result

    customers, orders, order_items, products

Spotting anomalies in a real table

Picture a single enrolments sheet: student_name, student_email, course_code, course_title, teacher_name. Three anomalies hide inside.

Update anomaly: a teacher changes their name and you must update every row for every course they teach. Miss one and reports disagree.

Insert anomaly: you want to add a new course before anyone enrols. There is no row to put it in without inventing a fake student.

Delete anomaly: the last student leaves a course, you delete the row, and the course title and teacher disappear with it.

The quick test for any table: if I change this one fact, how many rows must change? If the answer is "more than one", that fact probably belongs in its own table.

Denormalising on purpose, and doing it safely

Sometimes a join or an aggregate is too slow on a hot path, like showing comment counts on every post in a feed. Common, controlled denormalisations are:

A counter column (posts.comment_count) kept in sync by the same transaction that inserts a comment, or by a trigger. A materialised view for dashboards, refreshed on a schedule. A generated column (GENERATED ALWAYS AS (...) STORED) for a value computed from other columns in the same row, which Postgres keeps correct automatically.

Note that some copies are not denormalisation at all. order_items.unit_price is the price paid at that moment, a separate historical fact, and it must not change when the product price changes.

Before you denormalise, measure with EXPLAIN ANALYZE, try an index first, and write down who updates the copy and how you would rebuild it if it drifts.

  • Measure first; an index often fixes it
  • Counter column + trigger or same-transaction update
  • Materialised view for reports
  • Generated column for same-row calculations
  • Plan how to rebuild a drifted copy

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Apply 1NF, 2NF and 3NF~1h
  2. 2
    Spot update anomalies~1h
  3. 3
    Justify a deliberate denormalisation~1h

Key points

  • Update anomaly: a customer's city stored on every order goes out of sync.
  • Insert anomaly: you cannot record a fact without some unrelated data.
  • 3NF rule of thumb: every column describes the key, the whole key, and nothing else.
  • Justify denormalisation with a measured performance need and a sync plan.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
-- Before: orders(id, customer_name, customer_city, product, price)
-- customer_city repeats on every order -> update anomaly

CREATE TABLE customers (
  id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL,
  city text
);
CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers(id),
  ordered_at  timestamptz NOT NULL DEFAULT now()
);

Normalising a spreadsheet import

A shop imported a sheet: sales(invoice_no, invoice_date, customer_email, customer_name, sku, product_name, qty, unit_price). Step 1: the key of a row is (invoice_no, sku). Step 2: invoice_date and customer_email depend only on invoice_no (partial dependency), so they move to invoices. Step 3: customer_name depends on customer_email, a non-key column (transitive), so it moves to customers. Step 4: product_name depends only on sku, so it moves to products. unit_price stays on the line because it is the price paid on that invoice.

sql
CREATE TABLE customers (email text PRIMARY KEY, name text NOT NULL);
CREATE TABLE products  (sku text PRIMARY KEY, name text NOT NULL);
CREATE TABLE invoices (
  invoice_no     text PRIMARY KEY,
  invoice_date   date NOT NULL,
  customer_email text NOT NULL REFERENCES customers(email)
);
CREATE TABLE invoice_lines (
  invoice_no text REFERENCES invoices(invoice_no),
  sku        text REFERENCES products(sku),
  qty        int  NOT NULL CHECK (qty > 0),
  unit_price numeric(10,2) NOT NULL,
  PRIMARY KEY (invoice_no, sku)
);

A safe comment counter

The home feed shows 50 posts with their comment counts, and counting comments for each post on every page view is slow. Step 1: add posts.comment_count with default 0. Step 2: a trigger adds 1 on insert and subtracts 1 on delete, inside the same transaction, so the count cannot drift from normal writes. Step 3: keep a repair query that recomputes all counts, to run if a bulk load ever bypasses the trigger.

sql
ALTER TABLE posts ADD COLUMN comment_count int NOT NULL DEFAULT 0;

CREATE FUNCTION bump_comment_count() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
  ELSE
    UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
  END IF;
  RETURN NULL;
END $$;

CREATE TRIGGER comments_count AFTER INSERT OR DELETE ON comments
FOR EACH ROW EXECUTE FUNCTION bump_comment_count();

Quick reference

  • 1NF: one value per cell, no phone1/phone2/phone3 columns
  • 2NF: with a composite key, no column may depend on only part of it
  • 3NF: no column may depend on another non-key column
  • Test: if one fact changes, how many rows must change? More than one means split
  • Price paid on an order line is a historical fact, not a duplicate
  • Denormalise only after EXPLAIN ANALYZE shows a real problem an index can't fix
  • Generated column: total numeric GENERATED ALWAYS AS (qty * price) STORED

Common mistakes

  • Copying data "for speed" without measuring a real problem.
  • Over-normalising tiny lookup values into dozens of tables.
  • Forgetting that a price at order time is a fact worth storing on the order.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1order_items(order_id, product_id, qty, product_name) has key (order_id, product_id). Which normal form does product_name break?

Question 2

2employees(id, name, dept_id, dept_name). What is wrong?

Question 3

3You cannot add a new course until a student enrols in it. Which anomaly is this?

Question 4

4Which is the best first step before denormalising a slow page?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    contacts(id, name, phones) stores phones as '555-1, 555-2'. Redesign it to meet 1NF.

  2. Exercise 2medium

    Normalise loans(member_id, member_email, book_isbn, book_title, loaned_on, returned_on) to 3NF. One member can borrow the same book on different days.

  3. Exercise 3hard

    posts.comment_count is kept by a trigger, but a bulk import skipped triggers. Write one statement that repairs every count, including posts with zero comments.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need to normalise beyond 3NF?
Rarely. 3NF removes the anomalies that hurt most apps. BCNF, 4NF and 5NF handle unusual cases with overlapping keys or independent multi-valued facts.
Is storing JSON in Postgres against normalisation?
A jsonb column holding many values breaks strict 1NF, but it is fine for data you read and write as a whole. If you filter, join or enforce rules on the parts, use normal columns and tables.
Are data warehouses normalised?
Usually not fully. Analytics systems often use star schemas, where a big fact table joins to wide, deliberately denormalised dimension tables, because they are read far more than written.
ShareXLinkedInWhatsApp