What you'll learn: By the end of this lesson you will be able to use functional dependencies to find update, insert and delete anomalies, say what first, second, third and Boyce-Codd normal form each remove, split a table without losing information, decide when a deliberate copy earns its cost, and name the three ways a copy stays in step with its source, using a PostgreSQL lab that runs every step.
Picture a contact list where every envelope you ever addressed also carries the recipient's phone number. When a friend changes number you must find and correct every envelope, and if you miss one your records disagree. One address book that the envelopes point to fixes that, at the price of a lookup each time you write an envelope.
Normalization stores each fact in one place so it cannot disagree with itself. Denormalization copies a fact back next to where it is read, because the lookup got too expensive. Databases Basics gives both in a paragraph; this lesson is the dedicated treatment, with a lab that shows each failure happening.
Verified with PGlite 0.6.1 (PostgreSQL 19.0, the engine the lab reports), the PostgreSQL 18 documentation, Kent's "A Simple Guide to Five Normal Forms" and the Microsoft Learn normalization article, on 2026-12-01.
The core idea
A column belongs in a table only if it describes that table's key, the whole key and nothing but the key. A fact stored in several rows must be changed in all of them or the data contradicts itself. Normalize to remove that risk; copy data back only where a measured read cost justifies it, and then build the machinery that keeps the copy honest.
Three illustrations run through the lesson:
- Minimal example: a wide eight-row table, split into keyed tables in the lab.
- Realistic example: ShopStream's order history page.
- Failure example: a copied total that drifts, and a picker rule that stops being a key.
Functional dependencies: the idea underneath
A functional dependency X -> Y says that rows with the same X always have the same Y. A shopper_id tells you the email, so shopper_id -> email. An order_id does not tell you a product name, because an order has many lines, so order_id -> product_name is false.
A dependency is a rule about the business, not a fact about today's data: a query can refute one but never prove it. A key is a minimal set of columns that determines every other column; a superkey is any set that contains a key.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0):
Functional dependencies the data obeys (a check on this data, not a proof about the business):
order_id -> shopper_id: true
order_id -> store_id: true
shopper_id -> shopper_name, shopper_email: true
store_id -> store_name: true
product_id -> product_name: true
order_id -> product_name: false
Figure 1. The five tables the lab splits the wide table into. How to read this: each box is a table, PK marks a key and FK a column that points at another table's key. The lines read left to right as "one shopper places many orders". Each dependency above now sits in the table whose key determines it.
The anomalies a wide table invites
Kent's guide states the purpose: "The normalization rules are designed to prevent update anomalies and data inconsistencies." Against order_lines_flat there are three:
- Update anomaly. A fact is stored in several rows and a change reaches only some.
- Insert anomaly. A fact cannot be stored until an unrelated fact exists: a product cannot be recorded before someone orders it.
- Delete anomaly. Removing one fact removes another: cancelling the only order with a product erases the product.
Expected output, captured from a real run (the three anomalies):
== 2. The three anomalies in the wide table ==
Update anomaly: a buggy job changes Asha's email on one row only.
order_id product_id shopper_name shopper_email
-------- ---------- ------------ --------------------
101 1 Asha asha.new@example.com
101 2 Asha asha@example.com
103 2 Asha asha@example.com
103 3 Asha asha@example.com
shopper_id -> shopper_email: BROKEN
Insert anomaly: add the product Oat milk, which nobody has ordered yet.
error: null value in column "order_id" of relation "order_lines_flat" violates not-null constraint
Delete anomaly: cancel order 104, the only order that contains Frozen peas.
rows_naming_frozen_peas
-----------------------
0
The insert fails because order_id is part of the primary key, so it cannot be null.
The normal forms in plain words
Each normal form closes one more way for a fact to be in the wrong place. These are working definitions; sources word the formal ones differently.
| Form | Rule in plain words | A ShopStream violation |
|---|---|---|
| 1NF | One value per cell, no repeating groups of columns | product_1, product_2, product_3 columns on an order |
| 2NF | With a composite key, every other column depends on the whole key | product_name in order_lines (depends on product_id alone) |
| 3NF | No column depends on another non-key column | shopper_email in orders (depends on shopper_id) |
| BCNF | Every determinant (left side of a dependency) is a key | a picker who alone decides a category, in a table keyed by order |
Kent's phrase: "a non-key field must provide a fact about the key, the whole key, and nothing but the key." Second normal form "is violated when a non-key field is a fact about a subset of a key"; third "is violated when a non-key field is a fact about another non-key field". The Microsoft Learn article says third normal form "is considered the highest level necessary for most applications".
Third normal form is a table per fact
Splitting by dependencies gives Figure 1. The split must be lossless: joining the pieces must give exactly the original rows, which the lab proves with EXCEPT both ways. The keys now refuse bad data:
Expected output, captured from a real run (the keys after the split):
The foreign key refuses an order for a shopper that does not exist:
error: insert or update on table "orders" violates foreign key constraint "orders_shopper_id_fkey"
And the primary key refuses a second row for the same order and product:
error: duplicate key value violates unique constraint "order_lines_pkey"
Note that unit_price_cents stays on order_lines: the price paid is a fact about the sale, and taking it from a product table would let a later price change rewrite history.
Boyce-Codd normal form: the gap 3NF leaves
BCNF is "a slightly stricter version of the third normal form": for every non-trivial dependency X -> Y, X must be a superkey. Third normal form also accepts a dependency whose right-hand columns are all part of some candidate key; BCNF removes that exception.
The lab's pick_tasks shows it. Each order and category has one picker, and each picker works one category, so (order_id, category) -> picker_id and picker_id -> category. The key is (order_id, category), but picker_id decides category and is not a key.
Expected output, captured from a real run (the dependencies and the update anomaly):
== 4. Third normal form is not the end: a table that is not in BCNF ==
order_id category picker_id
-------- -------- ---------
101 ambient 3
101 chilled 1
102 chilled 1
103 ambient 3
103 frozen 2
104 frozen 2
(order_id, category) -> picker_id: true
picker_id -> category: true
The key is (order_id, category), but picker_id alone decides category and is not a key.
Update anomaly: picker 3 moves from ambient to bakery, one row is updated by hand.
picker_id -> category: BROKEN
Splitting into picker_category and order_pickers makes one update enough, at a cost the lab prints:
Expected output, captured from a real run (what the split gives up):
The price: the rule 'one picker per order and category' is no longer a key.
before, pick_tasks refused a second chilled picker for order 101:
error: duplicate key value violates unique constraint "pick_tasks_pkey"
after the split, order_pickers accepts it: accepted
"One picker per order and category" used to be a key, so the database enforced it. It no longer is, so a trigger or application code must. A BCNF decomposition cannot always keep every dependency as a key, which is why many designs stop at 3NF and handle such a case on purpose.
Figure 2. Reading one dependency against the normal forms. How to read this: start with a single dependency and follow the answers. The fix is nearly always a new table keyed by the determinant; the forms differ in which dependencies they let stay.
Build it: normalization and denormalization on PostgreSQL
This is the minimal example, a lab you can run on PGlite, the real PostgreSQL server compiled to WebAssembly and run in-process. PGlite 0.6.1 reports PostgreSQL 19.0 while the course targets PostgreSQL 18, so the lab uses only features the 18 manual documents. It is single-connection and in-memory: no lock waits between sessions, no server settings.
Setup. From examples/postgres-labs, after npm install:
node --test labs/normalization-vs-denormalization/test.mjs
cd labs/normalization-vs-denormalization && node run.mjs
The first command runs 12 tests. The code is in examples/postgres-labs/labs/normalization-vs-denormalization/.
How it works. The data is a hand-made illustrative sample: 3 shoppers, 2 stores, 4 products, 4 orders, 8 lines. Section 5 builds order_summary, one row per order with shopper name, store name, line count and total copied in, and a view order_summary_truth that always recomputes them:
create table order_summary as select * from order_summary_truth;
-- drift check: rows where the copy differs from the truth
select s.order_id from order_summary s join order_summary_truth t using (order_id)
where (s.shopper_name, s.store_name, s.line_count, s.total_cents)
is distinct from (t.shopper_name, t.store_name, t.line_count, t.total_cents);
Steps. Run the tests, then the demo. In section 5 the lab first prints the plan of the read with and without the copy: the join plan has three nested loops over four tables, the summary read scans one table, and with so few rows it claims nothing about speed. Then it changes the source without telling the copy:
Expected output, captured from a real run (the drift, then the same two changes with triggers installed):
Drift: copies are only as good as the code that keeps them in step.
orders whose summary row is stale: [101,102,103]
order_id copied_name true_name copied_total true_total
-------- ----------- --------- ------------ ----------
101 Asha Asha K 490 490
102 Ben Ben 430 1670
103 Asha Asha K 860 860
Triggers close the gap, and every write now does more work:
orders whose summary row is stale: []
order_id shopper_name line_count total_cents
-------- ------------ ---------- -----------
101 Asha K 2 490
102 Ben 2 1670
103 Asha K 2 860
104 Chen 2 570
The drift check names orders 101, 102 and 103: two stale copies of Asha's name and one total (order 102's real total is 1670, the copy says 430). After two PL/pgSQL triggers are installed, one on order_lines and one on renames in shoppers, the same updates leave nothing stale. The last step shows a materialized view going stale until REFRESH MATERIALIZED VIEW.
Break it. In NORMALIZE_SQL remove references shoppers from orders: the orphan-order check no longer fails. Remove the lines_sync trigger: the trigger test fails. Restore both and re-run the tests.
Stretch. Replace the summary table with a plain view and compare the plans.
What the model leaves out. Concurrent sessions, trigger cost under load, realistic table sizes, and PostgreSQL 18 itself.
Denormalization: the deliberate copy
When a hot read path is dominated by the join, a copy trades write cost and consistency risk for read speed. The forms, from least to most machinery:
- Derived column. A count or total on the parent row; drifts if any path forgets it.
- Copied attribute. A name or status on a child row; stale after a rename.
- Summary table. A row per entity, like
order_summary; fails when a write path bypasses the sync. - Materialized view. A stored query result, stale between refreshes.
The PostgreSQL manual calls the summary table a use of triggers: "The resulting summary can be used in place of the original table for certain queries — often with vastly reduced run times." A materialized view "may be refreshed later using REFRESH MATERIALIZED VIEW"; an ordinary view is "not physically materialized".
Three ways a copy stays in step
- In the same transaction. A trigger or the application writes both. PostgreSQL runs a trigger "as part of the same transaction as the statement that triggered it, so if either the statement or the trigger causes an error, the effects of both will be rolled back". The copy is never stale; every write does more.
- Asynchronously. An outbox, a change stream or a job rebuilds it later. Writes stay cheap and reads are briefly stale: the shape of a search index or cache.
- On a schedule or on demand. A refresh or a nightly rebuild: cheapest to write, stalest to read.
Whichever you choose, add a drift check: a query that recomputes the truth and counts disagreements.
Figure 3. The copy and the machinery around it. How to read this: writes go to the normalized tables, a trigger carries each change into order_summary, and the History API reads only the copy. The scheduled drift check recomputes from the source and compares, so a missed sync shows up as a number, not a complaint.
Trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Normalized, 3NF | One home per fact, keys enforce rules | Reads join tables | A measured hot read is too slow even with indexes |
| Summary table with triggers | One-table read, never stale | Every write does more, triggers must cover every path | Write volume is the bottleneck |
| Materialized view | No write-path cost | Stale until refreshed | Readers cannot tolerate staleness |
| Cache or read model outside the database | Scales reads separately | Another system and staleness story | Data must be strongly consistent |
In practice: ShopStream's order history page
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every number is illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's stage targets are 500,000 orders per day and a peak of about 58 checkouts per second (illustrative, from the course's shared numbers). The order history page lists a shopper's recent orders with store name, item count and total. It joins orders, stores, shoppers and order_lines on every load.
Starting architecture
Figure 4. The starting read path. How to read this: every page view runs the join and the aggregate. The question is whether that is a measured problem, not whether it looks inelegant.
Options considered
| Option | Read cost | Write cost | Risk |
|---|---|---|---|
| A. Stay normalized, index the foreign keys | Low if the plan is right | None | Needs a measured plan first |
B. order_summary kept by triggers |
One-table read | Each line change rewrites a summary row | A write path that skips the trigger |
| C. A read model rebuilt from events | Scales separately | Async pipeline | Staleness and another system |
The PostgreSQL manual says a foreign key declaration "does not automatically create an index on the referencing columns" and that "it is often a good idea to index the referencing columns too", so option A starts with the plan.
The decision
A first: add the indexes, capture the plan, measure the page. B is allowed only if the measured latency still misses the page's budget, only for the list view, and only with a drift check in monitoring. The detail page, which needs exact figures, keeps reading the normalized tables.
Rollout and verification
Behind a flag, a small share of shoppers read order_summary while the old query runs for comparison. Verification is three numbers: the drift check returns zero, sampled totals equal recomputed totals, and the latency percentile improves.
The 2 a.m. failure
The page reads: shoppers see a different total in history than on their receipt. A refunds feature adjusts order_lines.qty from a batch job written to run with triggers disabled for speed, so the summary kept the old totals. The nightly drift check shows about 4,000 stale rows (illustrative).
The checks: run the drift query, see which job touched the named orders, confirm the triggers are enabled. The mitigation is to rebuild the stale rows from the truth view, as the lab's refresh_order_summary does. The lasting fix is to route the batch through the same function and alert when the drift count exceeds zero.
Architect's notes
- Name the dependency before you split. If you cannot say which column determines which, you cannot say which table owns it.
- Normalize by default, denormalize by evidence. A plan and a latency target justify a copy; a feeling does not.
- History is not redundancy. The price paid belongs on the row that made the sale.
Common mistakes
- Treating a data check as proof. The data satisfied a dependency today; the business rule decides tomorrow.
- Copying first, measuring never. The slow page may be a missing index.
- Syncing only the happy path. Bulk jobs and imports also write.
Key takeaways
- A functional dependency is a business rule; each normal form restricts which dependencies a table may carry.
- 1NF removes repeating groups, 2NF partial-key dependencies, 3NF dependencies between non-key columns, BCNF every determinant that is not a key.
- A wide table invites update, insert and delete anomalies; keyed tables remove them, and a split must be lossless.
- BCNF can give up a rule the database used to enforce.
- Denormalize only a measured hot read, with a sync mechanism and a drift check.
Practice exercises
Exercise 1 (20 min). For deliveries(delivery_id, courier_id, courier_phone, order_id, store_id, store_city), list the dependencies and the normal form each violates.
Exercise 2 (45 min). Run the lab. Add store_city to stores and to order_summary, and extend the truth view and triggers.
Exercise 3 (1 hour). Update order_lines in a way that bypasses the trigger and predict the drift query's result first.
Exercise 4 (2 hours). Design the history page for ten times the lab's volume: choose among options A, B and C, and write the verification numbers and the alert.
Related reading
- Databases Basics: the relational model, ACID, indexes and the overview of this topic.
- SQL vs NoSQL: A Decision Framework: when document and wide-column models make copying the default.
- Cassandra and DynamoDB Modelling: denormalizing by design, one table per query.
- ShopStream Stage 3: Choosing the Right Data Store for Each Job: the order tables this lesson normalizes.
Official documentation
- PostgreSQL 18: Constraints.
- PostgreSQL 18: Trigger functions in PL/pgSQL and Overview of trigger behavior.
- PostgreSQL 18: CREATE VIEW and CREATE MATERIALIZED VIEW.
- William Kent, A Simple Guide to Five Normal Forms in Relational Database Theory.
- Microsoft Learn: Database normalization description.