Part 09 / Stage 3
Data modeling
Goal: Turn written requirements into tables — find the entities, draw their relationships, choose keys, normalize to third normal form, and know when (and why) to stop. Time: ~2 hours
What you will learn
- From requirements to entities, attributes and relationships
- Reading and sketching ER diagrams
- Cardinality: one-to-one, one-to-many, many-to-many and junction tables
- Choosing keys: natural vs surrogate, composite, UUID vs bigint
- Normalization: 1NF, 2NF, 3NF (and where BCNF fits)
- When to denormalize — the trade you are actually making
- Naming conventions that survive a growing team
This part designs on paper more than it types — but every claim that can run, runs, on shopdb as always.
Topics in this part
Practice
SQL workbench — write and run queries here
Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.
Design exercises want paper first; the SQL ones run against shopdb as always.
Exercise 1: The library, on paper
Scenario: "Members borrow books. Books can have several authors, and authors write several books. Each loan has a due date; late returns collect fines."
What to do: No SQL yet — list the entities (finishing "one row = one …" for each), every relationship with its cardinality, and where due_date and author_name must live. Sketch the ER diagram.
💡 Hint: count the many-to-manys — there is exactly one, and it needs a junction. The solution file holds a reference design to compare against.
Show the solution to Exercise 1
-- Exercise 1: The library, on paper — reference answer as comments.
-- Entities (one row = one ...):
-- books one title the library owns (isbn kept UNIQUE, surrogate book_id)
-- authors one writer
-- book_authors junction: one (book, author) pairing — books have co-authors,
-- authors write many books
-- members one registered borrower
-- loans one lending event: which copy, which member, when out, when due,
-- when returned (NULL while still out)
-- fines one fine raised against a loan
-- Relationships:
-- books >—< authors many-to-many -> book_authors junction
-- members —< loans one-to-many
-- books —< loans one-to-many
-- loans —< fines one-to-many (a loan can gather several fines)
-- 3NF checks that catch the classic traps:
-- * author_name lives on authors, never on books (2NF/3NF)
-- * member_city lives on members, never on loans (3NF)
-- * due_date lives on loans (it is a fact about the lending, not the book)
SELECT 'design exercise - see comments' AS note;
Exercise 2: Build the junction
What to do: Give shopdb products and tags: a tags table (bestseller, gift), a product_tags junction, and these pairings — Laptop Pro 14 and SQL for Beginners are bestsellers; SQL for Beginners and Chef Knife are gifts. List each tag's products, then prove the composite key rejects a duplicate pairing.
Sample output:
tag | products
------------+----------------------------------
bestseller | Laptop Pro 14, SQL for Beginners
gift | Chef Knife, SQL for Beginners
(2 rows)
ERROR: duplicate key value violates unique constraint "product_tags_pkey"
DETAIL: Key (product_id, tag_id)=(1, 1) already exists.
💡 Hint: composite PRIMARY KEY (product_id, tag_id); the rejected re-insert is the design working.
Show the solution to Exercise 2
-- Exercise 2: Build the junction
CREATE TABLE IF NOT EXISTS tags (
tag_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS product_tags (
product_id integer REFERENCES products(product_id) ON DELETE CASCADE,
tag_id integer REFERENCES tags(tag_id) ON DELETE CASCADE,
PRIMARY KEY (product_id, tag_id)
);
INSERT INTO tags (name) VALUES ('bestseller'), ('gift') ON CONFLICT DO NOTHING;
INSERT INTO product_tags VALUES (1, 1), (5, 1), (5, 2), (7, 2)
ON CONFLICT DO NOTHING;
-- Every product per tag:
SELECT t.name AS tag, string_agg(p.name, ', ' ORDER BY p.name) AS products
FROM product_tags pt
JOIN tags t ON t.tag_id = pt.tag_id
JOIN products p ON p.product_id = pt.product_id
GROUP BY t.name ORDER BY t.name;
-- The composite key rejects the same pairing twice:
INSERT INTO product_tags VALUES (1, 1);
Exercise 3: Normal-form detective
What to do: Name the violated normal form and the fix, for each:
(a) orders(order_id, customer_email, product_list) where product_list is "laptop, cable, book".
(b) order_items(order_id, product_id, product_name, quantity).
(c) employees(employee_id, department, department_budget).
💡 Hint: one is a list, one depends on part of the key, one depends on a non-key. The solution file explains each with the update that goes wrong.
Show the solution to Exercise 3
-- Exercise 3: Normal-form detective — answers in comments.
-- (a) orders(order_id, customer_email, product_list) breaks 1NF:
-- product_list is a non-atomic list. Split to one row per line.
-- (b) order_items(order_id, product_id, product_name, quantity) breaks 2NF:
-- product_name depends on product_id alone (part of the key).
-- Move it to products.
-- (c) employees(employee_id, department, department_budget) breaks 3NF:
-- department_budget depends on department, not on the employee.
-- Split out a departments table.
-- Proof of the 2NF pain in (b): if product 5's name changes, every order
-- line holding the old spelling is silently wrong. One fact, many places.
SELECT 'design exercise - see comments' AS note;
Exercise 4: Key audit
What to do: Using \d (or pg_constraint, as the solution does), audit shopdb's key choices: where are surrogate keys + UNIQUE natural candidates, where is a composite key, and which table hand-assigns plain integers? Say in a sentence whether each choice holds up.
Sample output (solution's catalog query):
conname | contype | relname
---------------------+---------+-------------
customers_pkey | p | customers
customers_email_key | u | customers
events_pkey | p | events
order_items_pkey | p | order_items
(4 rows)
💡 Hint: customers is the textbook surrogate+UNIQUE pair; order_items' row is a pairing; employees' hand-numbered ids are tolerable only because the table is tiny reference data.
Show the solution to Exercise 4
-- Exercise 4: Key audit on shopdb — answers verified against \d output.
-- customers: surrogate customer_id + UNIQUE(email) -> textbook default
-- order_items: composite PK (order_id, product_id) -> the row IS the pairing
-- employees: plain integer PK, hand-assigned (no identity) -> fine for a tiny
-- reference table; an identity column would be the production habit.
-- events: bigint identity -> right call: event streams grow without bound.
SELECT c.conname, c.contype, t.relname
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname IN ('customers', 'order_items', 'events')
AND c.contype IN ('p', 'u')
ORDER BY t.relname, c.contype;
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Lists in a column ("red, blue, green") | Can't filter, join or count properly | 1NF — one row per value (or a real array type, Part 14, when items are truly atomic) |
| Customer facts on the orders table | Update anomalies, drifting copies | Normalize to 3NF; point with a foreign key |
| Email as primary key | One address change cascades everywhere | Surrogate key + UNIQUE email |
| Foreign keys on both sides for many-to-many | Can't represent it; data gets faked | Junction table |
| Denormalizing "for simplicity" | Unowned copies drift; nobody notices | Normalize first; denormalize measured pain, with a refresh path |
| Naming by mood | uid/user_id/userid across tables |
A written half-page convention, day one |
Quick recap
- Nouns become entities and verbs become relationships; one row stands for one clearly nameable thing.
- ER diagrams force the one-or-many question at both ends, before SQL exists.
- A 1:N relationship is a foreign key on the many side, M:N takes a junction table (which may carry its own facts), and 1:1 is rare and shares a key.
- Use surrogate keys by default and keep the natural candidates UNIQUE; bigint serves inside one database, uuid when ids are minted in many places.
- The normal forms stack up: 1NF makes values atomic, 2NF ties facts to the whole key, and 3NF to the key alone — until every fact lives in exactly one place.
- Denormalize only deliberately — it buys a read win at the price of a consistency obligation.
- Pick one naming convention and write it down: snake_case, with foreign keys keeping the name of the column they reference.
Checklist
Before Part 10, make sure you can:
- Extract entities and relationships from a paragraph of requirements.
- Sketch shopdb's ER diagram from memory, crow's feet included.
- Explain why order_items exists and what its primary key is.
- Spot 1NF/2NF/3NF violations in a flat table and split it correctly.
- Argue natural vs surrogate keys in two sentences.
- Say when you would denormalize, and what you owe afterwards.
Read more: PostgreSQL's own DDL chapter opener shows these concepts as the manual presents them; the identity columns section covers surrogate keys.