Lesson 12 of 29Designing schemas
Normal Forms and When to Denormalise
Spot update, insert and delete anomalies, normalise to 3NF and BCNF step by step, then denormalise on purpose with counters, materialised views and star schemas.
Somebody exports orders to a spreadsheet, the spreadsheet becomes a CSV, and the CSV becomes a table called order_lines. It works for months. Then a customer moves city, support updates "the" row, and the next report shows the same customer living in two places. Normalisation is the discipline that prevents this: store each fact once, in the one place it belongs, so it cannot disagree with itself. Interviewers ask about normal forms constantly, and at work you need the other half too: knowing when to break the rules on purpose, and how to keep the copies honest.
The problem: one wide table
Here is the shop's data flattened into one spreadsheet-style table, one row per order line, the way an export or a quick prototype would store it. Every row repeats the customer's name and city and the product's name and category.
Press Run (⌘ Enter) to see what happens.That one table shows all three classic anomalies:
- Update anomaly: a fact stored many times must be changed many times. Miss one copy and the data contradicts itself. Ada now lives in London and Cambridge.
- Delete anomaly: deleting one fact destroys an unrelated one. Removing order 6 removed the only record that the book "SQL Performance Explained" exists.
- Insert anomaly: you cannot record a fact until an unrelated one exists. A new customer who has not ordered yet has no row, unless you fill the order columns with NULLs. Katherine Johnson and Barbara Liskov are already missing from this table for exactly that reason.
Match each situation to the anomaly it shows.
Functional dependencies in plain words
Normal forms are defined with one idea. A functional dependency A → B means: if you know A, there is exactly one possible B. Knowing a product_id tells you its product_name, so product_id → product_name. Knowing an order_id tells you the order date and the customer, so order_id → order_date, customer_id. Knowing customer_id tells you the customer's name and city.
Write down the dependencies in the wide table and the problem is plain:
(order_id, product_id) → unit_price_cents, quantity. These depend on the whole key. Good.order_id → order_date, customer_id. These depend on only part of the key.product_id → product_name, category_name. Also only part of the key.customer_id → customer_name, customer_city. These depend oncustomer_id, which depends onorder_id. A chain.
Dependencies come from the business rules, not from the data you happen to have. Ten rows where every product has one name do not prove product_id → product_name. The rule "a product has one name" does. That is why modelling starts with questions, as you saw in Modelling Data: Entities and Relationships.
1NF, 2NF, 3NF: the decomposition
Each normal form removes one kind of bad dependency. You get there by splitting the table along its dependencies.
First normal form (1NF): every column holds one value, and there are no repeating groups. A tags column holding 'sql,postgres' breaks it. So do columns named product_1, product_2, product_3. Our wide table is already in 1NF because each row is one order line. "Atomic" depends on how you use the value: a jsonb document or a Postgres array is fine if you never need to query or constrain its parts on their own, and a problem as soon as you do.
Second normal form (2NF): 1NF, and no non-key column depends on only part of a composite key. The key here is (order_id, product_id), and order_date depends on order_id alone. Move order facts to orders and product facts to products. What stays on the line is only what needs both ids: the price paid and the quantity. A table with a single-column key is automatically in 2NF.
Third normal form (3NF): 2NF, and no non-key column depends on another non-key column. In the new orders table, customer_city depends on customer_id, not on the order. That is a transitive dependency, order_id → customer_id → customer_city. Move customer facts to customers. Products have the same issue with category names, so categories get their own table.
Start: one row per order line, key (order_id, product_id). It is in 1NF: one value per cell, no repeating columns.
The split must be lossless: joining the pieces back must give exactly the original rows, no more and no fewer. You can check that in SQL. Build the normalised tables from the wide one, rebuild the wide view with joins, and compare in both directions with EXCEPT.
Press Run (⌘ Enter) to see what happens.Seventeen lines became six customers, ten orders and nine products, each stored once. If the DISTINCT on customers had returned more rows than there are customer ids, the PRIMARY KEY would have rejected the insert, which is the database telling you the "dependency" did not really hold in the data. That is a useful test when you normalise a messy import.
enrolments (student_id, course_id, grade, course_title) has the key (student_id, course_id). Which normal form does it break, and why?BCNF in one example
3NF has a loophole. Boyce-Codd normal form (BCNF) closes it with a stricter rule: for every dependency A → B, A must be a key (or contain one). The loophole only appears when a table has overlapping candidate keys, which is rare, but it is a favourite follow-up question.
Take tutoring: tutoring (student, subject, tutor). The rules are that each tutor teaches exactly one subject, and each student has one tutor per subject. So (student, subject) is a key, and also tutor → subject. That table is in 3NF, because subject is part of a key, so the dependency is allowed by 3NF's definition. But tutor is not a key, so it breaks BCNF, and the anomaly is real: if a tutor switches subject, you update every one of their students' rows.
The BCNF fix splits it into tutor_subjects (tutor PRIMARY KEY, subject) and student_tutors (student, tutor). The catch, and the reason seniors do not always do this: the rule "one tutor per subject per student" now spans two tables, so a simple UNIQUE constraint can no longer enforce it. BCNF decompositions can lose constraints that 3NF keeps. You pick the form whose trade-off you can live with.
Fourth and fifth normal forms deal with independent multi-valued facts in one table, such as a person's skills and languages stored as every combination. In practice, if each table describes one entity or one relationship, you rarely meet them.
When to denormalise
A normalised schema is the right default for the source of truth in a transactional system, which databases call OLTP (online transaction processing). Writes touch one row, and data cannot contradict itself. The price is joins and aggregation at read time, and on hot paths that price can matter.
Denormalising means deliberately storing a derived copy of data to make reads cheaper. It is a performance optimisation, so do it when a measurement says you need it, not in the first migration. The common cases:
- Counters:
posts.comment_countinstead ofCOUNT(*)over millions of comments on every page view. - Read-heavy hot paths: a product listing page that would otherwise join five tables per row.
- Reporting tables: daily revenue per category, computed overnight.
- Search documents: a flattened copy of a product with its category and brand, sent to OpenSearch.
- Caches: a rendered JSON blob in Redis.
Every copy needs two answers written down: what is the source of truth, and how does the copy stay in sync. The options are the same transaction as the write (simple, exact, but slows writes), a database trigger (cannot be forgotten by one code path, but hidden from app developers), or an asynchronous job or change-data-capture stream (no write cost, but the copy is stale for a while). Whichever you pick, add a reconciliation query that recomputes the value from the source and reports drift. Copies drift. The only question is whether you notice.
Here is a counter kept by triggers, with a bug that is very common in real code: someone handled INSERT and DELETE, and forgot UPDATE.
Press Run (⌘ Enter) to see what happens.What does this print?
-- USB-C Hub (product 3) starts with units_sold = 3 -- (2 on order 1, 1 on order 5). Triggers exist for INSERT and DELETE only. UPDATE order_items SET quantity = 5 WHERE order_id = 1 AND product_id = 3; SELECT units_sold FROM products WHERE id = 3;
Counters have a second problem under load: every new order line updates the same product row, so concurrent writers queue on that row's lock. High-traffic systems batch counter updates or keep per-shard counters and sum them. You will see why in Locking and Deadlocks.
Materialised views: denormalisation the database manages
A regular view is a saved query that runs every time. A materialised view in PostgreSQL stores the result like a table, so reads are fast, and you refresh it when you choose.
CREATE MATERIALIZED VIEW category_revenue_daily AS
SELECT date_trunc('day', o.created_at) AS day, p.category_id,
sum(oi.quantity * oi.unit_price_cents) AS revenue_cents
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY 1, 2;
-- Required for CONCURRENTLY: a unique index on plain columns, covering every row
CREATE UNIQUE INDEX ON category_revenue_daily (day, category_id);
-- Rebuilds the data without blocking readers (takes longer than a plain refresh)
REFRESH MATERIALIZED VIEW CONCURRENTLY category_revenue_daily;A plain REFRESH MATERIALIZED VIEW takes a lock that blocks reads until it finishes. CONCURRENTLY lets reads continue by computing the new result and applying the differences, and it only works if the view has a unique index. Either way the refresh recomputes the whole query: PostgreSQL has no built-in incremental refresh, so a view over a huge table can take minutes to refresh. Schedule it (with pg_cron or your job runner) and show users how fresh the data is. SQLite has no materialised views, so people build the same thing with a table and a scheduled INSERT ... SELECT.
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_summary fails with an error asking for an index. What is missing?OLTP versus OLAP: star schemas
Analytics (OLAP, online analytical processing) turns the trade-off upside down. Queries scan millions of rows and aggregate them. Writes come in bulk loads, not one row per user click. Warehouses such as BigQuery, Snowflake, ClickHouse and DuckDB store data by column, so reading three columns of a hundred-column table only reads those three, and repeated values compress extremely well. There, wide denormalised tables are cheap and joins are the expensive part, so warehouses denormalise by design.
The classic warehouse model is the star schema. In the middle is a fact table: one row per event you measure, such as fact_sales (date_key, product_key, customer_key, quantity, revenue_cents). Around it are dimension tables that describe the facts: dim_date (day, week, month, holiday flag), dim_product (name, category, brand flattened together), dim_customer (city, segment). Dimensions are deliberately denormalised: category name sits right on dim_product, so a report joins each dimension once instead of walking a chain.
When a dimension changes, such as a customer moving city, warehouses often keep both versions as separate rows with valid-from and valid-to dates, so last year's sales still report under last year's city. That pattern is called a slowly changing dimension (type 2), and it is the warehouse version of the snapshot idea from the modelling lesson.
The practical split at most companies: a normalised Postgres for the product, and data copied out (by a nightly job or a change-data-capture stream) into a warehouse with star schemas for analytics. The fact_sales table is a denormalised copy whose source of truth is still Postgres.
- functional dependency
- A → B: knowing A determines exactly one value of B. Normal forms are defined in terms of these.
- anomaly
- An update, insert or delete problem caused by storing a fact in a table whose key is about something else.
- 2NF
- No non-key column depends on only part of a composite key.
- 3NF
- No non-key column depends on another non-key column (no transitive dependencies).
- BCNF
- For every functional dependency A → B, A is a key. Stricter than 3NF, and occasionally loses a constraint.
- materialised view
- A stored query result in PostgreSQL that is fast to read and recomputed on REFRESH. CONCURRENTLY needs a unique index.
- star schema
- A warehouse model with a central fact table of measurements and denormalised dimension tables around it.