Data modelling
What breaks
Section titled “What breaks”The salon platform from lesson 1.3 started with one table. It looked like the owner’s notebook: one row per booking.
| booked_at | customer | phone | service | price | stylist |
|---|---|---|---|---|---|
| 5 Dec 10:00 | Ada Obi | 0803 111 2222 | Braids | ₦15,000 | Tolu |
| 5 Dec 14:30 | Ada Obi | 0803 111 2222 | Braids | ₦15,000 | Tolu |
| 6 Dec 09:00 | Kemi Bello | 0812 333 4444 | Silk press | ₦8,000 | Tolu |
One table, no joins. The booking page writes a row and the owner’s phone reads them. It works.
Then the salon gets busy, and the table starts to go wrong.
Ada changes her phone number. Fourteen rows hold the old one. The update misses two, and Saturday’s reminder goes to a number she no longer uses. Which row is right? The table cannot say.
The owner raises braids to ₦18,000. She updates every row that says “Braids”, and last month’s receipts now say she charged ₦18,000 for work she sold at ₦15,000.
She adds knotless braids. It does not appear on the booking page, because the page lists services from bookings, and nobody has booked it yet. Then the only silk-press booking is cancelled and deleted, and silk press disappears from the menu, price and all.
Last, Kemi books a silk press and a trim in one visit. A second row repeats her name, phone and time,
and one visit now looks like two. A service_2 column works until someone books three.
None of this is a bug in the code. One table holds facts about four different things, so each fact is stored many times, or nowhere. Deciding those things, and where each fact lives, is data modelling.
Terms used in this lesson:
- An entity is a thing the system must tell apart from other things. Chen’s 1976 paper on the entity-relationship model: “An entity is a ‘thing’ which can be distinctly identified.” An attribute is one fact about it, such as a customer’s phone.
- A relationship is “an association among entities” (Chen). Its cardinality says how many of each side it allows: one-to-one, one-to-many or many-to-many.
- A primary key is the column, or columns, whose values uniquely identify each row (Codd, 1970). A foreign key is a column whose values are another table’s primary key.
- Normalisation is splitting tables so that each fact is stored once, on the thing it describes.
Mental model
Section titled “Mental model”Every fact has one home: the thing it is a fact about. Before you store a field, ask “what is this a fact about?” The phone is a fact about the customer. The list price is a fact about the service. The time is a fact about the appointment. If the answer is not the row’s own key, the field is in the wrong table.
Diagram
Section titled “Diagram”The notebook, split by that question. The line ends show cardinality: || is exactly one, o{ is
zero or more, |{ is one or more.
Ada’s phone now lives in one row. A new service exists before anyone books it. Kemi’s two services
are two rows under one appointment. And price_charged keeps last month’s receipt true while
list_price moves.
From a description to entities
Section titled “From a description to entities”Where do the boxes come from? Mark the nouns: “a customer books one or more services with a stylist at a time”. Nouns the system tells apart and keeps facts about are entities. Nouns that are only a value, such as a time, are attributes.
Is an appointment an entity, or a relationship between a customer, a stylist and a time? Chen says the choice is yours: “some people may view something (e.g. marriage) as an entity while other people may view it as a relationship.” This course’s rule of thumb: once a relationship has its own facts and its own life, make it an entity. An appointment has a status, is moved and cancelled, and reminders point at it.
Relationships and cardinality
Section titled “Relationships and cardinality”For each pair, ask two questions: how many of B can one A have, and how many of A can one B have?
- A customer has many appointments; an appointment has one customer. One-to-many. The “many”
side holds the foreign key,
appointment.customer_id. - An appointment includes many services; a service appears in many appointments. Many-to-many.
Neither table can hold the foreign key, so a third table holds one row per pair. PostgreSQL’s
manual does the same with orders and products: “A table can have more than one foreign key
constraint. This is used to implement many-to-many relationships between tables.” This join
table is
appointment_service, and its primary key is the pair. - One-to-one, such as a stylist and her staff profile, is usually one table.
Then ask whether each side is required. Can a customer book “anyone free”? Then
appointment.stylist_id is nullable. That is a product decision; say it aloud.
Facts that belong to the relationship
Section titled “Facts that belong to the relationship”Where does the price Kemi agreed go? Not on service, which holds today’s list price. Not on
appointment, since a visit with two services has two prices. It depends on the pair: this service in
this appointment. Chen saw this in 1976: “Note that relationships also have attributes.” His example,
an employee’s share of time on a project, “is neither an attribute of EMPLOYEE nor an attribute of
PROJECT, since its meaning depends on both the employee and project involved.”
So price_charged lives on the join table.
Keys and what happens on delete
Section titled “Keys and what happens on delete”Is Ada’s phone a good primary key? It was unique, and she just changed it. This course’s suggestion: a generated id for each entity, with phone or email as ordinary columns, unique where needed.
A foreign key is also a rule the database enforces. PostgreSQL: it “specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table.” That is referential integrity: no appointment for a customer who does not exist.
What happens when the referenced row is deleted? PostgreSQL gives the choice and the reason:
| On delete | What it does | When the manual says to use it |
|---|---|---|
CASCADE |
deletes the referencing rows too | the child “is a component of” the parent “and cannot exist independently” |
RESTRICT / NO ACTION |
refuses the delete (NO ACTION is the default) |
the two tables “represent independent objects” |
SET NULL |
clears the foreign key | the link “represents optional information” |
Deleting an appointment should cascade to its appointment_service rows, which are parts of it.
Deleting a booked service should be refused, since the two are independent; that refusal stops the
silk-press failure. The owner hides an old service with an active flag instead.
One cost: “the declaration of a foreign key constraint does not automatically create an index on the
referencing columns” (PostgreSQL). The owner’s “my day” screen filters by stylist, so
appointment.stylist_id needs its own index.
Normal forms: one question asked three ways
Section titled “Normal forms: one question asked three ways”Codd’s 1970 paper introduced normalisation for “the problems of redundancy and consistency”. William Kent’s 1983 guide states the normal forms in plain words. Each builds on the one before.
First normal form (1NF): one shape per row. Kent: “all occurrences of a record type must contain
the same number of fields”, which “excludes variable repeating fields and groups.” The service_2
column broke it. The fix was a row per service, in the join table.
Second normal form (2NF): a fact about the whole key. It matters only when the key has more than
one column. Kent: it “is violated when a non-key field is a fact about a subset of a key.” Suppose
appointment_service also held service_name. It depends on the service alone, half the key, so a
rename leaves old rows wrong.
Third normal form (3NF): a fact about nothing but the key. Kent: it “is violated when a non-key
field is a fact about another non-key field”. The notebook, keyed by booking, held phone, a fact
about the customer. That is Ada’s failure.
Kent sums up both: “a record is in second and third normal forms if every field is either part of the key or provides a (single-valued) fact about exactly the whole key and nothing else.”
What do the failures share? When a fact sits in the wrong table, Kent says, it is repeated in every row, a change must update every row, the data “might become inconsistent”, and if no row happens to exist, “there may be no record” to keep the fact in. These are the three anomalies: the update anomaly (Ada’s phone), the insert anomaly (knotless braids, invisible until booked) and the delete anomaly (silk press, gone with its last booking). Normalisation makes them impossible, not just unlikely.
Higher forms exist; fourth normal form forbids “two or more independent multi-valued facts about an entity” in one table. This lesson stops at third.
Not every copy is redundancy
Section titled “Not every copy is redundancy”Isn’t price_charged a copy of list_price? It starts as the same number, but it is a different
fact. list_price answers “what does braids cost today?”, a fact about the service. price_charged
answers “what did Ada agree to pay on 5 December?”, a fact about that line of that appointment. When
the owner raises the price, the first must change and the second must not. Each depends on its own key.
This course’s test for any copy: if the source changes, should this change too? If yes, it is redundancy and should be a reference. If no, it is its own fact, like the address on a delivered order, and reading it through a join to today’s row is the bug.
Denormalising on purpose
Section titled “Denormalising on purpose”Kent names the cost at the start: the rules “tend to penalize retrieval”, since data from one record may have to come from several. And he does not make it a rule: “There is no obligation to fully normalize all records when actual performance requirements are taken into account.”
So when do you copy on purpose? When a read is hot, the join is expensive, and you can say how the
copy stays correct. The catalogue page shows each service’s average rating over thousands of reviews.
Store it on service, and every write path must update it in the same transaction (lesson 1.5), or
the two disagree.
The other tool is a materialized view, a stored query result. PostgreSQL: reading one “is often much faster than accessing the underlying tables directly or through a view, the data is not always current; yet sometimes current data is not needed.” A monthly revenue report can be a day old. An appointment’s start time cannot.
Not everyone starts from normal form. AWS’s DynamoDB guide sets the views side by side: “For an RDBMS, you can go ahead and create a normalized data model without thinking about access patterns”, while for DynamoDB “you shouldn’t start designing your schema … until you know the questions it will need to answer.” Lesson 1.6 covers that trade.
Doing it in an interview
Section titled “Doing it in an interview”Step 4 of lesson 0.2 is “Data”. In this course’s view, run it in this lesson’s order, aloud: entities from the nouns; relationships with cardinality; keys, with each many-to-many as a join table; “what is this a fact about?” for each field; then the main reads and their indexes, and only then a named, costed copy.
Real case
Section titled “Real case”Roost is a booking platform for businesses that sell their time. A salon visit fits the diagram above. A tailor’s dress does not: one agreement unfolds over a consultation, a fitting and a pickup, with work between them that books no time.
The problem. If the appointment holds everything, a dress becomes three appointments that each claim part of the price, and nothing says they are one sale.
The design. Four entities, split by what each fact is about:
- The job is the agreement: what the customer agreed to pay, what has been paid, when it is due.
- A line is one thing sold within the job, with its own agreed price. It may refer to an offering in the catalogue, but only as a reference: the offering fills the line in when it is created and never decides it afterwards. A tailor may agree more than her list price; that is the agreement, not an error.
- A stage is progress the owner chooses to track, such as cutting or fitting. It carries no money.
- An appointment is calendar time held for the job, and may name the stage it serves.
Which lines a stage works on is many-to-many, so it is its own join table, set by the owner and never guessed by the server.
Two rules came out of it. An earlier version let a stage carry its own price, so a figure lived in two places. Money moved to the job and its lines: one home per fact. And to place a fact on the job or the appointment, the test is whether it stops being true when the slot moves. “Tolu is doing the fitting” survives a reschedule; “Tolu is busy from 14:00 to 15:00” does not.
The trade-off. A salon that only books visits still has a job and a line behind each appointment, so a simple booking writes more rows and the job page reads several tables.
Honest about scale. Roost is early-stage and its tables are small. The model was chosen for meaning, not load. At much larger scale, the job page’s read would be the first candidate for a precomputed copy, with the cost of keeping it in step.
Trade-offs
Section titled “Trade-offs”Normalise or denormalise. Normalised tables make anomalies impossible, at the cost of joins on reads. A denormalised copy makes one read fast and makes every write responsible for it. This course’s suggestion: third normal form first, then denormalise only a measured read, and say in one sentence how the copy stays correct.
Entity or relationship. Promoting a relationship to an entity gives it an id and a home for its facts, for the cost of a table and a join. Keep a plain join table while the link has no life of its own.
Restrict or cascade. RESTRICT protects history and pushes an archive flag into the model.
CASCADE suits parts of a thing and is a dangerous default for independent things.
Drill 1 — interview question
Section titled “Drill 1 — interview question”“Design the data model for a salon booking platform. Customers book one or more services with a stylist at a time. Owners set prices and can change them. Show the tables, keys and relationships.”
Model answer
Entities. Customer, stylist, service, appointment. Time and price are attributes.
Relationships. A customer has many appointments (appointment.customer_id). A stylist has many
appointments (appointment.stylist_id, nullable if “anyone free” is allowed). Appointments and
services are many-to-many, through appointment_service keyed by the pair.
Facts placed. Name and phone on customer. Name, list price and duration on service. Start time and
status on appointment. The price agreed at booking on appointment_service, because it depends on the
pair and must not change when the list price does.
Keys and deletes. Generated ids, not phones. An appointment’s delete cascades to its service rows; a booked service’s delete is refused, and it is archived instead. Index stylist and start time.
Rubric
- Names the four entities and treats time and price as attributes — 2
- States each relationship’s cardinality and puts the foreign key on the “many” side — 2
- Uses a join table for appointments and services — 2
- Puts the agreed price on the join table and explains why it is not a copy of the list price — 2
- Chooses delete rules and indexes with a reason — 2
Total 10. 8 or more is a pass.
Drill 2 — interview question
Section titled “Drill 2 — interview question”The interviewer follows up: “The catalogue page shows each service’s average rating, and it is slow: every view averages thousands of reviews. A colleague says ‘just store the average on the service’. Does that break normal form? Would you do it, and how do you keep it right?”
Model answer
Yes, it is a derived copy. The average is a fact about the reviews, computable from them, so
storing it on service is denormalisation.
It can still be right. The read is hot and reviews are rare next to page views.
Keep it right. Store a review count and a rating sum on service, updated in the same transaction
as the review insert, so they cannot disagree after a crash. Handle review edits and deletes too, and
keep a scheduled task that recomputes from the reviews to repair drift.
Or don’t copy. If the page may be minutes stale, a materialized view or a cache (lesson 2.4) spares the write paths, at the cost of stale reads.
Rubric
- Identifies the stored average as denormalisation, a derived copy — 2
- Justifies it by the read pattern, not by habit — 2
- Updates the copy in the same transaction as the write — 3
- Covers edits and deletes and a way to repair drift — 2
- Names a stale-read alternative and its cost — 1
Total 10. 8 or more is a pass.
Drill 3 — hands-on exercise
Section titled “Drill 3 — hands-on exercise”Build the notebook, watch it fail, then fix it, in SQLite.
- Create the notebook from the opening: ten bookings, three customers, four services.
- Change Ada’s phone in only some rows, and query her numbers. Delete the only booking of one service, then list every service and its price. What is missing?
- Split the table into the five tables of the diagram. Run
PRAGMA foreign_keys = ON;first: SQLite leaves foreign keys “disabled by default”, for each connection. - Set
ON DELETE CASCADEfromappointment_servicetoappointmentandON DELETE RESTRICTtoservice. Predict what each delete does, then try both. - Raise one list price. Predict whether last month’s revenue query changes, then run it.
- Write “Tolu’s day”: every appointment on one date with customer name and services. Run
EXPLAIN QUERY PLAN, add an index on stylist and start time, and run it again.
Write one sentence per step on what surprised you.
Exit test
Section titled “Exit test”Answer without notes.
- In a one-to-many relationship, which table holds the foreign key, and why? How do you store a many-to-many?
- Name the update, insert and delete anomalies, with one example of each from a single booking table.
- State second and third normal form in one sentence each, and show one field that breaks each.
- Where does the price a customer agreed at booking live, and why is it not a redundant copy of the service’s price?
- When would you choose
CASCADEand whenRESTRICT? Name one value you would store derived on purpose, and what it costs.
Further reading
Section titled “Further reading”- Peter Chen, The Entity-Relationship Model — Toward a Unified View of Data (1976) — https://www.csc.lsu.edu/~chen/pdf/erd-5-pages.pdf.
- E. F. Codd, A Relational Model of Data for Large Shared Data Banks (1970) — https://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf.
- William Kent, A Simple Guide to Five Normal Forms in Relational Database Theory (1983) — https://www.bkent.net/Doc/simple5.htm. Sections 1 to 4.
- PostgreSQL 19, Constraints — https://www.postgresql.org/docs/current/ddl-constraints.html; and Materialized Views — https://www.postgresql.org/docs/current/rules-materializedviews.html. Checked 2026-11-29.
- SQLite, Foreign Key Support — https://www.sqlite.org/foreignkeys.html.
- AWS, NoSQL design for DynamoDB — https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html. Checked 2026-11-29.