Normalization: one fact in one place
Imagine the first version of the shop stored everything in one wide table:
| order_id | customer_email | customer_name | product_names | total |
|---|---|---|---|---|
| 1001 | ana@example.com | Ana | Mug, Notebook | 14.40 |
| 1002 | ana@example.com | Ana | Mug | 9.90 |
It looks convenient, until things change:
- Ana changes her email. It’s stored in every order, so you must update all of them. Miss one, and the data disagrees with itself.
- “Which orders contain a Mug?” means searching inside the text
'Mug, Notebook'. - A new customer who hasn’t ordered yet can’t be stored at all: there’s no order row to put them in.
NormalizationNormalizationDesigning tables so each fact is stored once, in the table it describes.Open in glossary → fixes this with one idea: store each fact once, in the table where it belongs, and point to it by id. The rules have names, the normal forms:
- First normal form (1NF): one value per cell. No lists like
'Mug, Notebook'. A list becomes rows in another table (order_items). - Second (2NF) and third (3NF): every column describes the thing the row is about, and nothing else.
customer_emaildescribes a customer, not an order, so it moves tocustomers, and the order keeps onlycustomer_id.
A memorable summary of 3NF: every column depends on the key, the whole key, and nothing but the key.
After normalizing, we get exactly the shop schema from the first lesson: customers, products, orders and order_items. Ana’s email lives in one row. Changing it changes it everywhere.
- Functional dependencies are the formal basis:
X → Yif a value of X determines Y. 2NF removes partial dependencies on part of a composite key (inorder_items(order_id, product_id, product_name),product_namedepends only onproduct_id). 3NF removes transitive dependencies (orders.customer_id → customer_email). BCNF tightens 3NF for tables with overlapping candidate keys; rarely an issue in practice. 4NF/5NF deal with independent multi-valued facts (a person’s skills and languages in one table). - Why it matters: update, insert and delete anomalies; constraints can only protect a fact stored once; smaller rows and indexes.
- 1NF and modern types: PostgreSQL arrays and
jsonbtechnically allow lists in a cell. They’re fine for data you read and write as a whole (a list of image URLs, a settings blob) and wrong for data you filter, join, count or reference with foreign keys (tags you search by, line items). - OLTP vs analytics: transactional schemas aim for 3NF; warehouses deliberately denormalize into star schemas (fact tables plus wide dimension tables) because they’re read-mostly and scanned in bulk.
- Modeling choices interviewers probe: surrogate vs natural keys, nullable column vs separate table (sparse optional data), one-to-one splits (rarely worth it except for very wide or sensitive columns), soft deletes (
deleted_at) and their effect on unique constraints (partial unique indexWHERE deleted_at IS NULL), and multi-tenancy (tenant_idon every table, in every index and unique key).
Predict the output
Lessons store their tags as text: 'sql,joins' or 'nosql,mongodb'. Which lessons does this return?
SELECT id, title FROM lessons WHERE tags LIKE '%sql%';'%sql%' matches any text containing 'sql', including 'nosql' and 'postgresql'. Patterns like '%,sql,%' get complicated at the start and end of the list and still can't use an index. A tags table (lesson_tags(lesson_id, tag)) makes it WHERE tag = 'sql': exact, indexable, and countable.
-- instead of lessons.tags = 'sql,joins'
CREATE TABLE lesson_tags (
lesson_id bigint NOT NULL REFERENCES lessons (id) ON DELETE CASCADE,
tag text NOT NULL,
PRIMARY KEY (lesson_id, tag)
);
CREATE INDEX lesson_tags_tag ON lesson_tags (tag);
-- lessons tagged sql, exactly
SELECT l.id, l.title
FROM lessons l
JOIN lesson_tags t ON t.lesson_id = l.id
WHERE t.tag = 'sql';
-- the most used tags
SELECT tag, count(*) FROM lesson_tags GROUP BY tag ORDER BY count(*) DESC LIMIT 10;The email that changed only once
Tap the line with the bug.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
customer_email text NOT NULL,
total numeric(10, 2) NOT NULL
);
-- "change email" endpoint
UPDATE customers SET email = 'ana.p@example.com' WHERE id = 42;Hint: Where else does Ana's email live after this UPDATE?
customer_email copies a fact about the customer into every order. The endpoint updates customers, but Ana’s 37 orders still say ana@example.com. Order confirmations, receipts and support searches now use whichever copy they happen to read. Fixing it means updating every copy, every time, in every code path, forever.
Remove the copy and read the email through the foreign key:
ALTER TABLE orders DROP COLUMN customer_email;
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = 1001;There’s one exception, covered in the next part: if the business needs “the email the receipt was sent to” as a historical record, that’s a different fact (the email at the time of the order), and storing it is correct. The bug is storing a copy by accident and expecting it to stay current.
Deep diveDesigning a schema in an interviewInterview favorite
“Design the database for a ride-sharing app” (or a booking system, a library, a chat). A structure that works:
- Clarify the main use cases and their volumes: request a ride, match a driver, track the trip, pay, rate. Which reads are hot (“my trips”, “nearby drivers”), which writes are frequent (locations every 4 seconds)?
- Find the entities and their keys: users, drivers (a user with extra data: one-to-one or a role), vehicles, trips, payments, ratings. Surrogate keys; natural identifiers (
email, license plate) getUNIQUE. - Relationships and cardinality: a trip has one rider and one driver (FKs on
trips); a driver has many vehicles but one active (a partial unique indexWHERE active); a trip has many location points (child table, or not in the database at all). - Normalize to 3NF, then name the deliberate copies: the fare and pickup address on the trip (historical facts), the driver’s average rating (a cached aggregate).
- State and history:
trips.statuswith allowed values (CHECKor a lookup table) and timestamps per transition, or an append-onlytrip_eventstable for auditing. - Indexes from the hot queries:
trips (rider_id, created_at DESC),trips (driver_id) WHERE status = 'IN_PROGRESS', a geo index for driver locations (or Redis, since they change every few seconds and don’t need durability). - Constraints that encode rules: one active trip per driver (
UNIQUE (driver_id) WHERE status IN (…)), money asnumeric/cents,timestamptz. - What doesn’t belong in the OLTP database: high-frequency location pings, analytics, search. Say where they go and why.
Interviewers look for the reasoning (use cases → entities → constraints → indexes), deliberate trade-offs, and rules enforced by the database rather than by hope.
- Functional dependencies: 2NF (no partial dependencies on a composite key), 3NF (no transitive ones), BCNF rarely matters.
- Anomalies (update, insert, delete) are the argument; constraints only protect facts stored once.
- Arrays/
jsonbfor data used as a whole; child tables for anything filtered, joined, counted or referenced. - OLTP in 3NF, analytics in star schemas. Soft deletes need partial unique indexes; multi-tenant keys include
tenant_id.
Check this part
What does first normal form forbid?
orders has a customer_email column. What problem does it cause?
order_items(order_id, product_id, product_name, quantity) with key (order_id, product_id). Which normal form does product_name break?
When is a jsonb or array column a reasonable 1NF exception?