Model the domain & write the ER diagram
An ER diagram and DDL for a realistic app schema reviewed against 3NF.
By Invicly Tech, , in SQL & PostgreSQL. About 12 minutes to read.
In short
The capstone starts on paper: gather what the app must store, draw the entities and relationships, then write DDL and review it against 3NF before any data goes in.
Explained simply
Before you write a single CREATE TABLE, you need to know what the app must remember and what questions people will ask it. A library app, for example, must remember members, books and loans, and must answer questions like "which books are overdue?" and "how many loans did we have last month?"
From those notes you pick out entities: the main things the app is about, usually nouns such as member, book and loan. Then you work out relationships: one member can have many loans; one book can have many authors, and one author can write many books.
An ER diagram (entity relationship diagram) draws this as boxes and lines. Each box is a table with its columns and keys. The ends of each line show how many: one, or many (the crow's foot, a line that splits into three like a bird's foot).
Last, you turn the drawing into DDL (the SQL that creates tables) and check it against third normal form (3NF): every fact is stored once, in the table where it belongs. A schema that passes this review is much easier to keep correct as the app grows.
Press Play on a diagram to walk through it one step at a time.
- 1Gather requirements
User stories and the questions reports must answer
- 2List entities
Nouns: customer, product, order
- 3Map relationships
One-to-many, many-to-many, optional or required
- 4Draw the ER diagram
Boxes, keys and crow's-foot lines
- 5Write DDL
Types, keys and constraints
- 6Review against 3NF
Remove repeated facts, note deliberate exceptions
- 1Rule
A copy is lent to one member at a time
- 2Entities
copies and loans are separate tables
- 3Relationship
copies 1 to many loans over time
- 4Column
loans.returned_at, NULL while open
- 5Constraint
Unique copy_id where returned_at is NULL
In depth
Gathering requirements that shape the schema
Collect three kinds of notes. User stories say what people do: "A member borrows a copy of a book for 21 days." Business rules say what must always be true: "A copy can be on loan to only one member at a time" and "A member may hold at most 5 loans." Report questions say what the data must answer: "Top 10 most borrowed books this year" or "members with overdue loans".
Each note points at schema decisions. "Copy" and "book" are different entities, because the library owns several physical copies of one title. The 21-day rule means you need a due date. The report on overdue loans means you need both due_at and returned_at, not just a status text.
Ask about history early. Do you need to know who borrowed a copy two years ago? Then loans are never deleted, only closed. Questions like this are cheap to answer now and expensive to change later.
- Nouns become candidate tables
- Verbs between nouns become relationships
- Must, never and at most become constraints
- Reports tell you which columns and indexes you need
Reading and drawing relationships
For each pair of entities, ask two questions, one from each side. Can one member have many loans? Yes. Can one loan belong to many members? No. That is one-to-many, and the foreign key goes on the many side: loans.member_id.
If the answer is many from both sides (one book has many authors, one author has many books), you need a junction table, book_authors, with two foreign keys and a composite primary key. Junction tables can carry their own facts too, such as the author's position on the cover.
Also decide optional or required. Every loan must have a member, so member_id is NOT NULL. A book may have no copies yet, so nothing forces a copy to exist. In crow's-foot notation, a bar means exactly one, a circle means zero is allowed, and the crow's foot means many. Tools like dbdiagram.io, draw.io or pgAdmin's ERD tool can draw this for you from the DDL.
- members
- 1 to many: loans
- books
- 1 to many: copies
- many to many: authors via book_authors
- copies
- 1 to many: loans (one open at a time)
- loans
- member_id, copy_id NOT NULL
- borrowed_at, due_at, returned_at
- authors
- many to many: books
Choosing types and constraints while modelling
Decide types and constraints at the same time as tables, because they are part of the design. Use bigint GENERATED ALWAYS AS IDENTITY for surrogate keys, text for strings (in PostgreSQL, varchar(n) is not faster, it only adds a length check), timestamptz for moments in time, date for calendar days, and numeric for money.
Turn every business rule you can into a constraint. NOT NULL for required fields. UNIQUE for natural keys like a member's email or a book's ISBN. CHECK for simple rules such as due_at > borrowed_at. Foreign keys with a deliberate ON DELETE choice: CASCADE for parts that cannot exist alone (book_authors rows), RESTRICT, or the default NO ACTION, for history you must keep (loans).
Some rules need more than a simple constraint. "Only one open loan per copy" becomes a partial unique index on loans(copy_id) WHERE returned_at IS NULL. "At most 5 loans" usually lives in application code or a trigger, so write down where it is enforced.
Reviewing against 3NF
Walk through each table and check three things. First normal form: every column holds one value, with no lists like authors = 'Smith, Lee' and no repeating columns like phone1, phone2. Second normal form: in a table with a composite key, every non-key column depends on the whole key, not just part of it; in book_authors, the book title would depend only on book_id, so it belongs in books. Third normal form: non-key columns depend only on the key, not on other non-key columns; storing member_city and member_postcode on every loan repeats facts about the member.
The practical test: if one real-world fact changes, how many rows must you update? The answer should be one.
Deliberate exceptions are fine when written down. Storing the loan's due_at, even though it could be computed from borrowed_at plus a policy, is correct, because the policy may change later while old loans keep their original due date.
- loans has member_name and member_email
- books has authors as a comma list
- copies repeats the book title
- Changing an email means many updates
- loans has member_id only
- book_authors junction table
- copies has book_id only
- Every fact stored once
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Gather requirements for the app~40m
- 2Draw the ER diagram~40m
- 3Write DDL and review against 3NF~40m
Key points
- Write down the questions the database must answer before designing tables.
- Every relationship needs a clear owner of the foreign key.
- Choose types and constraints while modelling, not later.
- Document any deliberate denormalisation and the reason for it.
Key terms
Tap a card to flip it. 0/4 known
Examples
-- e-commerce core (excerpt)
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(id),
status text NOT NULL CHECK (status IN ('cart', 'paid', 'shipped'))
);
CREATE TABLE order_items (
order_id bigint REFERENCES orders(id) ON DELETE CASCADE,
product_id bigint REFERENCES products(id),
qty int NOT NULL CHECK (qty > 0), unit_price numeric(10,2) NOT NULL,
PRIMARY KEY (order_id, product_id));DDL for the library core
This DDL follows the model. Note the junction table for authors, the CHECK on loan dates, the RESTRICT on loans so history cannot be deleted by accident, and the partial unique index that allows many closed loans per copy but only one open one.
CREATE TABLE members (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE, name text NOT NULL, joined_on date NOT NULL DEFAULT current_date);
CREATE TABLE books (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
isbn text NOT NULL UNIQUE, title text NOT NULL, published_year int);
CREATE TABLE authors (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL);
CREATE TABLE book_authors (book_id bigint REFERENCES books(id) ON DELETE CASCADE,
author_id bigint REFERENCES authors(id), PRIMARY KEY (book_id, author_id));
CREATE TABLE copies (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id bigint NOT NULL REFERENCES books(id), barcode text NOT NULL UNIQUE);
CREATE TABLE loans (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
member_id bigint NOT NULL REFERENCES members(id) ON DELETE RESTRICT,
copy_id bigint NOT NULL REFERENCES copies(id) ON DELETE RESTRICT,
borrowed_at timestamptz NOT NULL DEFAULT now(), due_at timestamptz NOT NULL,
returned_at timestamptz, CHECK (due_at > borrowed_at));
CREATE UNIQUE INDEX one_open_loan_per_copy ON loans (copy_id) WHERE returned_at IS NULL;Fixing a 3NF problem found in review
A first draft had loans(member_id, member_email, copy_id, book_title, ...). Step 1: ask what each column depends on. member_email depends on member_id, and book_title depends on the copy's book, not on the loan. Step 2: both are transitive dependencies, so they break 3NF. Step 3: drop them from loans; they already live in members and books. Step 4: confirm the report "overdue loans with member email and book title" still works with joins.
SELECT m.email, b.title, l.due_at
FROM loans l
JOIN members m ON m.id = l.member_id
JOIN copies c ON c.id = l.copy_id
JOIN books b ON b.id = c.book_id
WHERE l.returned_at IS NULL AND l.due_at < now()
ORDER BY l.due_at;Quick reference
- Write report questions first; they decide columns and indexes
- One-to-many: the foreign key goes on the many side
- Many-to-many: a junction table with a composite primary key
- Crow's foot = many, bar = exactly one, circle = zero allowed
- 3NF test: changing one real fact should update exactly one row
- Partial unique index enforces rules like one open loan per copy
- Use timestamptz for moments, date for days, numeric for money
- Write down every deliberate denormalisation and why
Common mistakes
- Designing tables before knowing what questions they must answer.
- Skipping constraints during modelling and never adding them later.
- Forgetting to store historical facts like the price at time of order.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write five report questions and three business rules for a library app, and list the entities they imply.
- Exercise 2medium
Add reservations: a member can reserve a book (not a specific copy), and the queue order matters. Write the DDL and state the relationships.
- Exercise 3hard
Review this draft table against 1NF, 2NF and 3NF and fix it: book_authors(book_id, author_id, book_title, author_name, author_country, position).
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Which tool should I use to draw the ER diagram?
- Any tool is fine: dbdiagram.io, draw.io, or pgAdmin's ERD tool, which can also generate diagrams from an existing database. What matters is that keys and cardinalities are shown clearly.
- Should I use natural keys like ISBN as primary keys?
- Usually use a surrogate identity key as the primary key and keep the natural key UNIQUE. Natural keys can change or be missing, and they make foreign keys bigger.
- Is 3NF always the goal?
- For the core write tables, yes. Reporting tables or caches can be denormalised on purpose, as long as you document why and how they stay in sync.