BEGINNERCHAPTER 03

Modelling: keys, normalisation, and when to denormalise

Design the shop schema from its requirements, learn which update anomaly each normal form prevents, then break a rule on purpose and keep it honest

55 MINDATABASESUPDATED 2026-11-02
PREDICT

A table order_lines(order_id, product_id, qty, customer_email) has primary key (order_id, product_id). A customer changes their email. What goes wrong?

A schema is a set of decisions about where each fact lives. Good schemas store each fact in one place, so that it cannot disagree with itself. Normalisation is the formal version of that rule, and it was developed because the alternative was discovered the hard way: tables where an update to one fact had to be made in hundreds of rows, where you could not record a product until someone ordered it, and where deleting an order deleted the only record of a customer.

This chapter designs the shop’s schema from its requirements, names the normal forms and the anomaly each one prevents, then does what every real schema does: breaks one rule on purpose, and puts a fence around the break.

From requirements to tables

The shop’s requirements, as a product manager would state them:

  • Customers register with an email and a name, from a country.
  • Products have a SKU, a name, a category and a price. Stock is tracked per product.
  • A customer places orders. An order has lines, each for a product with a quantity at the price charged. An order moves through placed, paid, shipped or cancelled.
  • A payment is attempted against an order through a provider and may fail, be captured or be refunded. An order may need more than one attempt.

The first pass at modelling is to find the entities, the things with identity that the business talks about, and the relationships between them. Customers, products, orders, payments are entities. “Stock per product” is an attribute of product or a one-to-one entity. “Order has lines” is a one-to-many relationship whose many side has its own attributes (quantity, price charged) and so becomes a table: order_items. “Payment against an order” is one-to-many from orders to payments, because of the sentence about more than one attempt.

The second pass is to ask, for each attribute, what determines it. That question is the whole of normalisation, so it gets its own section. The result is the six tables in docs/LABS.md, and every column of them is either an identifier, a foreign key, or an attribute that depends on the whole key of its table and on nothing else, with one deliberate exception that the end of the chapter is about.

Keys: natural or surrogate

Every table needs a primary key, and you have two choices for it. A natural key is a set of attributes the business already uses to identify the thing: email for a customer, sku for a product. A surrogate key is a number the database makes up: id bigint GENERATED ALWAYS AS IDENTITY.

The arguments for natural keys are real. They mean something, so a foreign key column is readable without a join. They enforce uniqueness of the business identifier for free. They avoid one index. The arguments against are what decide it in practice:

concern natural key (email) surrogate key (id)
changes customers change email; every foreign key must follow, cascading through orders never changes
size in foreign keys 20 to 40 bytes copied into every order row and every index on it 8 bytes
ambiguity case, trailing whitespace, plus-addressing; is A@x.com the same customer as a@x.com? none
composite keys an order line’s natural key is (order, product): two columns to copy into anything that references a line one column
exposure leaks the identifier into URLs and logs a bare integer leaks how many customers you have; use a public token for URLs if that matters

The shop uses surrogate keys everywhere and keeps the natural keys as UNIQUE constraints: customers.email, products.sku. That is the common recommendation and it is right most of the time. The exceptions are small, stable reference tables (ISO country codes, currencies) where the natural key is short and never changes, and inventory, whose key is product_id because there is exactly one stock row per product and the relationship is one-to-one.

docs/LABS.md writes the key type as bigserial. Postgres’s own wiki prefers identity columns (GENERATED ALWAYS AS IDENTITY) for new schemas because the sequence is owned by the column and ALWAYS stops an application from writing its own ids; the two are otherwise equivalent and both are bigint. Use bigint, not int: two billion orders is a real number for a shop that lasts, and the migration from int to bigint on a two-billion-row table is one of the worst days in the migrations chapter.

Functional dependencies

Normalisation is defined over functional dependencies. X → Y means: any two rows that agree on X must agree on Y. In products, id → sku, name, category, price_cents, and also sku → id because sku is unique. In orders, id → customer_id, status, total_cents, created_at, shipped_at. A candidate key is a set of attributes that determines every attribute in the table and has no subset that does.

The dependencies come from the requirements, not from the data. “A product has one category” is product_id → category. “An order belongs to one customer” is order_id → customer_id. If the requirement were “a product can be in several categories”, the dependency would not hold and categories would need their own table. Normalising a table means writing down its dependencies and checking them against the rules below. Each rule forbids a kind of dependency, and each forbidden dependency causes a specific anomaly.

The normal forms and their anomalies

First normal form (1NF): every attribute holds one atomic value, and there are no repeating groups. A tags text column holding 'sale,new,clearance' violates it; so do phone1, phone2, phone3. The anomaly is that you cannot query, index or constrain the individual values: “which products are tagged sale?” becomes a LIKE '%sale%' that also matches 'wholesale'. Postgres arrays and jsonb give you atomic-ish values with real operators and GIN indexes, which is why the strict reading of 1NF is debated; the practical rule is that if you ever need to join on, count or constrain the inner values, they belong in a table.

Second normal form (2NF): 1NF, and no non-key attribute depends on part of a composite candidate key. The Predict is the canonical example: order_lines(order_id, product_id, qty, customer_email) with order_id → customer_email. The fact is stored once per line and must be updated once per line. 2NF only has teeth when the key is composite; a table with a single-column surrogate key is in 2NF automatically, which is one reason surrogate keys make the next rule the one you actually meet.

Third normal form (3NF): 2NF, and no non-key attribute depends on another non-key attribute. The violation is a transitive dependency: order_items(id, order_id, product_id, qty, product_name) has id → product_id → product_name. Product name is a fact about the product, stored once per line that ever ordered it. Rename the product and you must update every line; misspell it in one import and you have two products. This is exactly the Why. The fix is always the same: the dependent attribute moves to the table whose key determines it, and you reach it with a join. The one-line summary, attributed to Bill Kent, is that every non-key attribute must depend on the key, the whole key, and nothing but the key.

Boyce–Codd normal form (BCNF): for every non-trivial dependency X → Y, X is a superkey. BCNF closes a gap in 3NF that appears only when a table has overlapping candidate keys. Suppose shipments are recorded as shipments(order_id, carrier, tracking_no), where one order can ship with several carriers, each shipment has one tracking number, and a tracking number identifies its carrier. Candidate keys are (order_id, carrier) and (order_id, tracking_no). The dependency tracking_no → carrier has a determinant that is not a superkey, but carrier is part of a key, so 3NF permits it. The anomaly: the fact “tracking number T belongs to carrier C” is repeated for every order that shares it, and a typo gives one tracking number two carriers. BCNF splits it into shipments(order_id, tracking_no) and tracking(tracking_no, carrier). You will meet this rarely; when you do, it is in tables with two natural identifiers for the same thing.

Fourth and fifth normal forms deal with multi-valued and join dependencies and almost never arise in a schema built from surrogate-keyed entities. Kent’s 1983 paper covers them in five pages if you want the whole set.

The anomalies, collected:

anomaly what happens prevented by
update one fact in many rows; a change misses some 2NF, 3NF, BCNF
insertion cannot record a fact until an unrelated fact exists (no product row until it is ordered) 2NF, 3NF
deletion deleting the last row that mentions a fact loses the fact (delete the only order, lose the customer) 2NF, 3NF
query cannot address an inner value (tags in a string) 1NF

Constraints make the model true

A normalised schema stores each fact once. Constraints make sure what is stored is a fact at all. Postgres gives you five kinds, and a schema that uses only the first is leaving the database’s cheapest guarantees on the table.

NOT NULL on every column that has no business meaning when absent: orders.customer_id, order_items.qty, payments.amount_cents. Only orders.shipped_at is nullable in the shop, and it is nullable because “not yet shipped” is a real state. PRIMARY KEY and UNIQUE make a bag into a relation and are the only way the planner can know a join is one-to-one. FOREIGN KEY guarantees every reference resolves, and its ON DELETE clause states the policy when the parent goes: RESTRICT (default behaviour: refuse), CASCADE (delete the children; right for order_items under orders), or SET NULL (right almost nowhere in a shop). CHECK encodes the rules the requirements stated in words: qty > 0, price_cents >= 0, status IN ('placed', 'paid', 'shipped', 'cancelled'), shipped_at IS NULL OR shipped_at >= created_at. A CHECK cannot reference another table, which is the main gap and the reason triggers exist.

A type is a constraint too. Money is stored as integer cents in the shop because float cannot represent 0.10 exactly and Postgres’s money type is tied to the server’s locale; numeric(12,2) is the other correct choice and costs a little more per row. country char(2) is a type-level promise of exactly two characters. timestamptz, not timestamp, for anything that happens at an instant, because timestamp without a zone is a wall-clock reading with no way to know which wall.

Denormalisation, on purpose

Every normalised schema eventually stores one derived fact. The shop’s is orders.total_cents. It is derivable: SELECT sum(qty * unit_price_cents) FROM order_items WHERE order_id = ?. Storing it is a 3NF violation in spirit (it depends on the order’s items, not on the order’s key alone), and it is there because the order listing page, the customer’s order history, and the revenue report all want the total without touching six million item rows.

Be precise about what is and is not denormalised. order_items.unit_price_cents looks like a copy of products.price_cents and is not. It is the price charged at order time; products.price_cents is the price now. They are different facts that happen to be equal at the moment of ordering, and the schema must allow them to differ. Copying a value at a point in time to freeze it is not denormalisation. Storing a value that must always equal a function of other current values is.

The risk of a derived column is drift: an item is inserted, its quantity updated, or a line deleted, and the total is not recomputed. Nothing fails. The order page shows one number and the item list adds up to another. The revenue report sums total_cents and finance reconciles against payments and finds a gap. It is the Why of this chapter in miniature: a fact stored in two places disagreeing with itself.

There are three ways to keep a denormalised column honest, in rising order of cost and falling order of risk.

A periodic check. A query that finds the disagreements, run on a schedule, with an alert when it returns rows. It does not prevent drift; it bounds how long drift lives. The query is the lab’s step 6. Run it nightly and you know your drift is at most a day old.

A trigger. An AFTER INSERT OR UPDATE OR DELETE trigger on order_items that recomputes the parent’s total. It cannot be bypassed by an application that forgets, because it runs inside the same transaction as the item change and the item change fails if the trigger fails. The cost is one extra UPDATE of the orders row per item change, and a row lock on the order for the rest of the transaction, which is also what makes two concurrent item inserts for one order serialise correctly. Triggers hide logic from the application developer reading the code, so document them where the order_items table is documented. Postgres triggers are written in PL/pgSQL and attached with CREATE TRIGGER ... EXECUTE FUNCTION.

A generated column. GENERATED ALWAYS AS (expr) STORED keeps a column equal to an expression of other columns in the same row, and Postgres 17 maintains it on every write; nothing can set it directly. It is perfect for line_cents = qty * unit_price_cents on order_items. It cannot compute orders.total_cents, because the expression may not reference other rows or tables, and Postgres 17 implements only stored generated columns (virtual ones arrive in a later release). So the generated column is the right tool one level down and the trigger is the right tool for the cross-table total.

The rule for choosing to denormalise at all: measure first. On a schema with the right indexes, sum() over one order’s three items is a few page reads and well under a millisecond. The listing page that shows fifty orders needs fifty such sums or one join to a pre-aggregated subquery, and that is still fast. The revenue report over two million orders is where the derived column earns its place, and a materialised view or a nightly summary table may earn it better. Denormalise when you have a query that is slow for a reason the indexes chapter cannot fix, and put the trigger in the same migration as the column.

LAB Design it, break it, fence it ~40 MIN
YOU NEEDDocker Desktop or Docker Engine with Composethe ATLAS repo cloned; labs/databases started with `docker compose up -d` and loaded with `docker compose exec -T db psql -U atlas -d shop -f /shop/load.sql` (add `-v scale=0.1` on a laptop under 8 GB)the previous chapter's lab done, so psql and the shop are familiar

Everything in this lab runs inside transactions you roll back, or in a scratch schema you drop, so the shop stays clean for the later chapters.

1. Read the schema as dependencies.

cd labs/databases && docker compose exec db psql -U atlas shop
\d orders
\d order_items
\d inventory
orders shows the primary key on id, a foreign key to customers and a check constraint orders_status_check limiting status to four values. order_items shows foreign keys to orders and products. inventory shows product_id as both the primary key and a foreign key: the one-to-one relationship written as a shared key. For each table say aloud what id → determines, and notice that orders.total_cents is the one column you cannot justify from the key alone.

2. Build the 2NF violation and watch the anomaly. A scratch schema keeps the shop untouched.

CREATE SCHEMA scratch;
SET search_path TO scratch, public;
CREATE TABLE order_lines AS
SELECT oi.order_id, oi.product_id, oi.qty, c.email AS customer_email
FROM public.order_items oi
JOIN public.orders o ON o.id = oi.order_id
JOIN public.customers c ON c.id = o.customer_id
WHERE o.customer_id = 42;
ALTER TABLE order_lines ADD PRIMARY KEY (order_id, product_id);
SELECT count(*), count(DISTINCT customer_email) FROM order_lines;
4 lines at scale 1 (7 at 0.1) and exactly 1 distinct email: one fact, stored N times. Now change the customer’s email on the lines of one order only, as a buggy app would: UPDATE order_lines SET customer_email = 'new@example.com' WHERE order_id = (SELECT min(order_id) FROM order_lines); and re-run the count. Two distinct emails for one customer. That is the update anomaly, and nothing in the table can forbid it, because the table has no way to express that the email depends on order_id alone.

3. The 3NF violation, and the insertion and deletion anomalies.

CREATE TABLE lines_with_names AS
SELECT oi.id, oi.order_id, oi.product_id, oi.qty, p.name AS product_name
FROM public.order_items oi JOIN public.products p ON p.id = oi.product_id
WHERE oi.order_id < 2000;
SELECT product_id, count(*), count(DISTINCT product_name) FROM lines_with_names GROUP BY product_id HAVING count(*) > 1 ORDER BY 2 DESC LIMIT 5;
DELETE FROM lines_with_names WHERE product_id = (SELECT product_id FROM lines_with_names GROUP BY 1 HAVING count(*) = 1 LIMIT 1);
The products that appear on more than one line have their name stored that many times (distinct count 1, for now). The DELETE removes the only line that mentioned some product, and with it the only record in this table of that product’s name: the deletion anomaly. Try to record a new product’s name without a line to put it on: you cannot, because id and order_id have no value. That is the insertion anomaly. public.products has neither problem because the name lives where its key is.

4. The constraints the shop should have. Add them in a transaction, then roll back so the later chapters see the schema as documented.

SET search_path TO public;
BEGIN;
ALTER TABLE order_items ADD CONSTRAINT order_items_qty_positive CHECK (qty > 0);
ALTER TABLE order_items ADD CONSTRAINT order_items_price_nonneg CHECK (unit_price_cents >= 0);
ALTER TABLE orders ADD CONSTRAINT orders_total_nonneg CHECK (total_cents >= 0);
ALTER TABLE orders ADD CONSTRAINT orders_shipped_after_created CHECK (shipped_at IS NULL OR shipped_at >= created_at);
INSERT INTO order_items (order_id, product_id, qty, unit_price_cents) VALUES (1, 1, 0, 100);
ROLLBACK;
Each ALTER takes a second or two at scale 1: Postgres scans the whole table to prove the constraint already holds, and the loader’s data satisfies all four. The status rule is not here because schema.sql already declares it (orders_status_check, and payments has the same for provider and status). The INSERT fails with new row for relation "order_items" violates check constraint "order_items_qty_positive". The ROLLBACK discards everything, constraints included. Note the time the ALTERs took: on a production table that scan holds a lock, and the migrations chapter shows NOT VALID plus VALIDATE CONSTRAINT to avoid it.

5. A generated column for the line total.

BEGIN;
ALTER TABLE order_items ADD COLUMN line_cents bigint GENERATED ALWAYS AS (qty * unit_price_cents) STORED;
SELECT id, qty, unit_price_cents, line_cents FROM order_items WHERE order_id = 1;
UPDATE order_items SET line_cents = 0 WHERE order_id = 1;
ROLLBACK;
The ALTER rewrites the six-million-row table to fill the column, which takes tens of seconds; the SELECT shows line_cents equal to the product on every row; the UPDATE fails with column "line_cents" can only be updated to DEFAULT. A generated column cannot drift because nothing can write to it. It also cannot reach another table, which is why step 7 needs a trigger.

6. Measure drift in orders.total_cents.

SELECT count(*) AS orders_checked,
       count(*) FILTER (WHERE o.total_cents <> coalesce(s.cents, 0)) AS drifted
FROM orders o
LEFT JOIN (SELECT order_id, sum(qty * unit_price_cents) AS cents FROM order_items GROUP BY order_id) s
  ON s.order_id = o.id;
2 000 000 checked (200 000 at 0.1) and drifted is 0, because load.sql computes each total from its lines. This query is the periodic check. It reads 8 million rows and takes a few seconds; as a nightly job that is fine, as an on-request check it is not, which is the argument for the trigger.

7. Introduce drift, then fence it with a trigger.

BEGIN;
UPDATE order_items SET qty = qty + 1 WHERE id = (SELECT min(id) FROM order_items WHERE order_id = 1);
SELECT o.total_cents, (SELECT sum(qty * unit_price_cents) FROM order_items WHERE order_id = 1) AS from_items
FROM orders o WHERE o.id = 1;
ROLLBACK;
The two numbers differ by one unit price. Nothing complained. Now add the fence:
BEGIN;
CREATE OR REPLACE FUNCTION recompute_order_total() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE target bigint;
BEGIN
  target := coalesce(NEW.order_id, OLD.order_id);
  UPDATE orders SET total_cents = coalesce((SELECT sum(qty * unit_price_cents) FROM order_items WHERE order_id = target), 0)
   WHERE id = target;
  IF TG_OP = 'UPDATE' AND NEW.order_id <> OLD.order_id THEN
    UPDATE orders SET total_cents = coalesce((SELECT sum(qty * unit_price_cents) FROM order_items WHERE order_id = OLD.order_id), 0)
     WHERE id = OLD.order_id;
  END IF;
  RETURN NULL;
END $$;
CREATE TRIGGER order_items_total AFTER INSERT OR UPDATE OR DELETE ON order_items
  FOR EACH ROW EXECUTE FUNCTION recompute_order_total();
UPDATE order_items SET qty = qty + 1 WHERE id = (SELECT min(id) FROM order_items WHERE order_id = 1);
SELECT o.total_cents, (SELECT sum(qty * unit_price_cents) FROM order_items WHERE order_id = 1) AS from_items
FROM orders o WHERE o.id = 1;
DELETE FROM order_items WHERE order_id = 1;
SELECT total_cents FROM orders WHERE id = 1;
ROLLBACK;
After the UPDATE the two numbers agree. After the DELETE the total is 0. The trigger ran inside the same transaction as each change, so there was no moment at which the order was visible with a stale total. The trigger’s SELECT does a sequential scan of six million rows per fired row because order_items has no index on order_id yet; in the indexes chapter that becomes three page reads. The ROLLBACK drops the trigger and the function along with the changes.

8. Clean up.

DROP SCHEMA scratch CASCADE;
DROP SCHEMA. The shop is as the loader left it, which the next chapters rely on.
Re-run step 7’s trigger block but change AFTER to BEFORE and RETURN NULL to RETURN NEW. The total is now wrong by exactly one row’s worth after every change: a BEFORE ROW trigger runs before the item row is written, so the recomputed sum does not include the change it is reacting to. Then go back to AFTER, open a second psql, and in each session run BEGIN; INSERT INTO order_items (order_id, product_id, qty, unit_price_cents) VALUES (2, 1, 1, 100); without committing. The second session blocks on the trigger’s UPDATE orders ... WHERE id = 2 until the first commits or rolls back. That row lock is what makes the total correct under concurrent inserts, and it is also a serialisation point on hot orders; the locking chapter is about the trade.
DECIDE

The order listing page shows 50 orders with their totals and loads in 40 ms. The revenue-by-day report sums item lines across two million orders and takes 6 s, which the finance team runs every morning. A developer proposes adding orders.total_cents, maintained by application code in the order service, to make both fast. Do you add the column, and how do you maintain it?

READING
  1. PAPER
    A Simple Guide to Five Normal Forms in Relational Database Theory William Kent, 1983

    Five pages, no algebra, one example per normal form, with the famous summary of 3NF. Read the whole thing; it is the shortest complete treatment that exists. Skip only the 5NF section until you have a table with three interlocking many-to-many relationships. Read: all of it; it is five pages (originally CACM 26(2)).

  2. PAPER
    A Relational Model of Data for Large Shared Data Banks E. F. Codd, 1970

    Section 1.4 is where normal form is first proposed, as a way to eliminate nested relations. Two pages; read it to see that normalisation began as a storage argument before it became a consistency argument. Read: section 1.4, Normal form.

  3. BOOK
    Designing Data-Intensive Applications, chapter 2: Data Models and Query Languages Martin Kleppmann, 2017

    Places the relational model against document and graph models and makes the case for each. The section on many-to-one and many-to-many relationships is this chapter's argument from the other side: when a document database is right because the data is a tree. Read: chapter 2, up to the end of the relational versus document comparison.

  4. BOOK
    Database Design for Mere Mortals Michael J. Hernandez, 2020

    The practitioner's book on going from interviews and requirements to tables, with a process you can follow. Chapters 6 to 10 cover fields, tables, keys and relationships without ever using the word dependency. Skip the parts about paper forms. Read: chapters 6 to 10 (analysing the current database through table relationships).

  5. DOC
    PostgreSQL 17: Constraints

    CHECK, NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY and EXCLUDE with their exact semantics, including how NULL interacts with CHECK (a NULL result passes) and the ON DELETE actions.

  6. DOC
    PostgreSQL 17: Generated Columns

    Two screens: what a generated column may reference, that only STORED is implemented in 17, and the rules that stop it drifting. Read before reaching for a trigger.

  7. DOC
    Don't Do This

    The Postgres wiki's list of schema mistakes: money, timestamp without time zone, char(n), serial over identity, and more, each with the reason and the fix. Read the data-types section now and the rest before the project.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Aggregation, window functions, CTEs →