Skip to content

Module 04 · Lesson 4.1

Modelling Entities and Relationships

40 minUpdated 19 Nov 2026Part of Data Modeling, APIs and Backend · New Project Creation
On this page
  1. What you will learn
  2. What a data model is
  3. Find entities and rules in your requirements
  4. One-to-many relationships and foreign keys
  5. Turn business rules into database constraints
  6. Step-by-step workflow
  7. What the assistant does and what you do
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

Before a builder lays a single brick, someone lists the rooms and decides which doors join them. A database needs the same plan. If the plan is wrong, every screen and every endpoint built on top of it inherits the mistake.

In this lesson you turn the Tidewell Physiotherapy requirements into a data model. You find the things the clinic keeps records about, decide how they link together and write down the rules the database must enforce. You also learn how to ask an assistant for a draft and check each table against a requirement before anything is built.

What you will learn

  • Find entities and their facts by reading the nouns in written requirements.
  • Describe one-to-many and many-to-many relationships in plain words and with foreign keys.
  • Turn business rules into constraints that the database enforces for you.
  • Use an AI assistant to draft a model, then trace every table back to a requirement.

Before you start

  • Completed Assistant Context Files, and have the Tidewell requirements from Acceptance Criteria or your own numbered requirements.
  • Access to any capable AI assistant.
  • Optional: Node.js and the project from earlier lessons, if you want to run the examples.

What a data model is

A data model is a plan for what your system remembers and how the pieces connect. Picture a filing cabinet. Each drawer holds one kind of form. Each form has boxes to fill in. Some forms carry a number that points to a form in another drawer.

The words below are used in every database course. You will meet them again in each lesson of this module.

Entity
A kind of thing the system keeps records about, such as a patient or a booking. It is one labelled drawer in the cabinet.
Attribute
One fact about an entity, such as a patient's email. It is one box on the form.
Relationship
A link between two entities, such as 'a booking belongs to one patient'. It works like a loan slip that carries a library card number.
Primary key
A value that identifies one record and never repeats, like a library card number.
Foreign key
A column that holds another record's primary key, so the database can check that the link is real.
Constraint
A rule the database enforces by itself, like a turnstile that lets only one person through at a time.

In a relational database such as PostgreSQL, each entity becomes a table, each attribute a column and each record a row. The model comes first. The tables are the model written in SQL, which is the topic of the next lesson.

Find entities and rules in your requirements

Read your requirements twice with two highlighters. On the first pass, mark the nouns: patient, clinician, slot, booking. They are candidates for entities. On the second pass, mark every sentence with words such as 'only', 'never', 'at most' or 'must'. They are candidates for constraints.

The table below does this for the Tidewell requirements. It is also a trace table: each piece of the model points back to the requirement that asked for it.

RequirementNouns and rulesModel piece
FR-01 See free slots for a clinician and dateClinician, slot, date. A slot is free when nobody holds it.clinicians, slots. 'Free' is worked out, not stored.
FR-02 Move or cancel your own bookingPatient, booking, status. Only the owner may change it.patients, bookings with a status and a patient_id.
FR-03 Offer a freed slot to the waiting listWaiting list, date range, optional clinician.waiting_list_entries.
FR-04 Staff act for a patientStaff member acting on someone's behalf.A role recorded on each change (accounts come in Module 6).
FR-05 Record who changed a booking and whenChange, actor, time. History is never rewritten.booking_changes, where rows are only ever added.
NFR-01 Two people cannot hold the same slotAt most one live booking per slot.A unique index limited to live bookings.
CON-01 Patient data under the clinic's dutiesKeep personal data small. No clinical notes.patients holds only name, email and phone.
Every table traces to a requirement. A table with no row here is a warning sign.

One-to-many relationships and foreign keys

A one-to-many relationship means one record on one side can be linked to many on the other. One clinician has many slots. One patient has many bookings. The 'many' side holds the foreign key: each slot stores the id of its clinician, like a loan slip that carries the library card number.

Text
clinicians 1 ---- * slots 1 ---- * bookings * ---- 1 patients
                              |
                              +- one live booking at most (NFR-01)

bookings 1 ---- * booking_changes     (FR-05: who, what, when)
patients 1 ---- * waiting_list_entries  (FR-03)
clinicians 1 ---- * waiting_list_entries (optional: blank means any clinician)

The Tidewell model. '1' means one, '*' means many. The star end holds the foreign key.

A many-to-many relationship, such as students and courses, needs a third table in the middle that holds one row per pair. Tidewell has no such pair, because a booking already joins one patient to one slot. If a visit ever needed two clinicians, you would add a link table for it.

Why a slot and a booking are separate

A slot is a time the clinic offers. A booking is something a patient does to it. Keeping them apart lets a slot exist before anyone books it, and lets the same slot be booked, cancelled and booked again by someone else.

Why cancelled bookings are kept

FR-05 asks for a record of every change. If a cancelled booking were deleted, its history would vanish. So the booking stays, with a status of 'cancelled', and a separate table adds one row for each change.

Turn business rules into database constraints

Code can have bugs, and two requests can arrive in the same instant. A rule that must never be broken belongs in the database, where it is checked on every write, whatever code sends it.

RuleConstraintTidewell example
A value must be presentNOT NULLA patient always has a name and an email.
A value must not repeatUNIQUETwo patients cannot share an email address.
A value must be one of a fewCHECKA booking status is 'booked' or 'cancelled', nothing else.
A link must point to something realFOREIGN KEY (REFERENCES)A booking cannot name a slot that does not exist.
Something must be unique only in some rowsPartial unique indexOne live booking per slot, but any number of cancelled ones.

The last row is the one that protects NFR-01. A partial unique index says: among rows that match a condition, this column must not repeat. Here the condition is 'status is booked'. It is like a theatre that allows one name tag per seat, counting only seats that are currently taken.

Relationships also answer questions. FR-01 asks for the free slots of one clinician on one day. This query keeps a slot only if no live booking points at it. The kit ran it against a real PostgreSQL engine with three slots on 1 December.

SQL
SELECT s.id::int AS slot_id, s.starts_at
FROM slots s
WHERE s.clinician_id = $1
  AND s.starts_at >= $2::date AND s.starts_at < $2::date + 1
  AND NOT EXISTS (
    SELECT 1 FROM bookings b WHERE b.slot_id = s.id AND b.status = 'booked'
  )
ORDER BY s.starts_at

Free slots for one clinician and day. $1 is the clinician id and $2 is the date. The query sits inside test-model.ts.

Output of test-model.tsCaptured from a real run
free before: 1@09:00 2@10:00 3@11:00
free after booking slot 2: 1@09:00 3@11:00
free after cancelling: 1@09:00 2@10:00 3@11:00

Slot 2 disappears while a live booking holds it and returns when the booking is cancelled. No flag was updated on the slot. The answer comes from the relationship.

Step-by-step workflow

  1. Step 1: List the nouns and rule words

    Read your requirements and acceptance criteria twice. Write each noun and each rule sentence on its own line.

    What you should see: A raw list that still contains duplicates and non-entities.

  2. Step 2: Decide what is stored and what is calculated

    Keep the things people create or change. Cross out anything you can work out from other data, such as 'free slot'.

    What you should see: A short list of entities.

  3. Step 3: Draw the relationships

    For each pair, ask: can one A have many Bs? Can one B have many As? Note which side holds the foreign key.

    What you should see: A diagram like the one above, with one star and one 1 on every link.

  4. Step 4: Write the rules as constraints

    For each rule sentence, pick a constraint type from the table. If a rule needs a decision, such as the notice period, leave it for code and note who owns it.

    What you should see: A list of constraints, each with its requirement ID.

  5. Step 5: Ask an assistant to challenge the model

    Use the prompt card. Treat its output as a list of suggestions, and mark each one accepted, rejected or 'ask the client'.

    What you should see: A reviewed list with every extra table explained or removed.

  6. Step 6: Trace and save

    Fill in the trace table and save the model in docs/data-model.md with the date. Tell the client in words how the system will treat a cancelled booking.

    What you should see: Every table and constraint points to a requirement ID.

From requirements to a model
  1. Requirements

    Nouns and rule words

  2. Entities

    Stored, not calculated

  3. Relationships

    One-to-many, foreign keys

  4. Constraints

    Rules the database enforces

  5. Assistant challenge

    Suggestions, not decisions

  6. Trace table

    Saved in docs/

Write the model in words and pictures first. SQL comes in the next lesson.

What the assistant does and what you do

An assistant is quick at drafting tables and spotting a missing link. It does not know your clinic. It fills gaps with what is typical, and typical systems have extras you did not ask for.

TaskAssistant's partYour part
List entities and attributesProposes a first draft from the requirements you paste.Cross out anything without a requirement ID.
Find relationshipsSuggests which side holds each foreign key.Check each one against how the clinic really works.
Suggest constraintsProposes NOT NULL, UNIQUE and CHECK rules.Decide which rules are real. Confirm business rules with the client.
Challenge the modelAsks 'what if two people book at once?' and similar questions.Answer from the requirements, or take the question to the owner.
Name thingsSuggests snake_case names.Keep names consistent with the contract and the glossary.

Conclusion and your next step

A good data model starts in words. Nouns become entities, links become foreign keys, and rules that must never break become constraints. Calculate what you can instead of storing it, and trace every table to a requirement.

Your next step: write the trace table for your own capstone, then continue to Database Schema and Migrations. There you turn this model into numbered SQL files and prove that the double-booking rule works.

For more practice with a similar clinic, try the Appointment Booking Portal project. To see how requirements shape a backend, read API-First Development: OpenAPI Contracts with AI.

Reusable prompt

Data model draft and challenge

Drafts a data model from numbered requirements, traces every table to a requirement and flags anything it added on its own.

You are helping me design a data model. Do not write SQL or code yet. Do not add anything that is not needed by a requirement.

Fictional clinic: Tidewell Physiotherapy. Out of scope: payments, insurer billing, clinical notes. Database: PostgreSQL.

Requirements:
FR-01 A patient can see the free slots for a chosen clinician and date.
FR-02 A patient can move or cancel their own booking without calling the clinic.
FR-03 When a booking is cancelled, the slot is offered to the waiting list.
FR-04 Front-desk staff can create, move and cancel bookings on a patient's behalf.
FR-05 Every change to a booking records who made it and when.
NFR-01 Two people changing the same slot cannot produce two bookings for it.
CON-01 Patient data is stored under the clinic's data-protection duties, so keep personal data to the minimum.

Tasks:
1. List the entities with their attributes, in plain words.
2. Describe each relationship as one-to-many or many-to-many and say which side holds the foreign key.
3. List the rules the database should enforce, as constraints, each with the requirement ID it serves.
4. Give a trace table: requirement ID, model piece.
5. List anything you added that no requirement asks for, under the heading "Not in requirements", so I can decide whether to remove it.
6. List questions I should ask the client. Do not answer them yourself.
Show the reusable template

Replace each {{placeholder}} with your own details.

You are helping me design a data model. Do not write SQL or code yet. Do not add anything that is not needed by a requirement.

Context: {{organisation_and_scope}}. Database: {{database}}.

Requirements:
{{numbered_requirements}}

Tasks:
1. List the entities with their attributes, in plain words.
2. Describe each relationship as one-to-many or many-to-many and say which side holds the foreign key.
3. List the rules the database should enforce, as constraints, each with the requirement ID it serves.
4. Give a trace table: requirement ID, model piece.
5. List anything you added that no requirement asks for, under the heading "Not in requirements", so I can decide whether to remove it.
6. List questions I should ask the client. Do not answer them yourself.

Expected output and limitations

A list of entities with attributes, relationships with the foreign-key side named, constraints tied to requirement IDs, a trace table, a separate 'Not in requirements' list and a list of questions for the client.

Sample responseIllustrative — your output will differ
Entities
  clinicians: display name, active
  patients: full name, email, phone
  slots: clinician, start time, end time
  bookings: slot, patient, status, created time, cancelled time
  booking_changes: booking, action, who (role and id), from slot, to slot, time
  waiting_list_entries: patient, optional clinician, earliest date, latest date

Constraints
  bookings: one live booking per slot (NFR-01)
  slots: end time after start time; one slot per clinician and start time
  patients: email unique

Not in requirements
  payments table, invoices, insurers, clinical_notes

Questions for the client
  Should a slot ever be removed, or only hidden?

Limitations to keep in mind

  • The draft is built from typical systems. Some suggestions will not fit the clinic and some needed pieces may be missing.
  • It may sneak in extras such as payments or notes. Anything without a requirement ID is removed or sent to the client.
  • It cannot tell you the clinic's rules. Notice periods, retention and who may see what are decisions for named roles.

Common errors and how to fix them

One big table holds everything: patient email, clinician name and slot time in every booking row.

Why it happens: It feels simple to start, so facts about different things were mixed.

Fix: Give each kind of thing its own table and link them with foreign keys, so a change is made in one place.

Cancelled bookings are deleted.

Why it happens: Delete looked like the natural meaning of cancel.

Fix: Keep the row with a status of 'cancelled' and record the change, so FR-05 can be met and the slot can be rebooked.

The model has tables or columns that no requirement mentions.

Why it happens: An assistant added what is typical, and nobody checked.

Fix: Build the trace table. Remove anything without a source, or record it as a candidate with a reason.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Model Ferngate's parts and stock movements

Ferngate Cycle Repairs wants mechanics to record parts taken from the store room for a job, and to flag low stock. Draft a data model for it, run the Data model draft and challenge prompt, and produce a final model with a trace table.

You will need

  • Requirement: a mechanic can record a part taken for a job.
  • Requirement: the system flags a part as low in stock. The threshold is 'to be agreed'.
  • Note: mechanics share one tablet, and the internet connection is unreliable.
  • Note: the owner reorders every Friday by counting shelves.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • Ask whether stock is one number you update, or the sum of movements in and out. Think about what you could check later.
  • A part taken for a job and a delivery from a supplier are both movements. What tells them apart?
Show a model answer

A strong answer keeps parts (what exists), jobs (what the work is) and stock movements (each time a quantity went in or out), and links each movement to one part and, for parts taken, to one job. Stock on the shelf is the total of movements, which means a wrong entry can be traced and corrected with a new movement instead of a silent overwrite. The low-stock threshold is a decision for the owner, so it appears as 'to be agreed', perhaps as a column that stays empty until then. A constraint such as 'a movement has a reason from a short list' helps reports. Rejecting an assistant's supplier or purchase-order table shows the scope held, because ordering is not in the requirements yet.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A requirement mentions a 'free slot'. How should the model treat it?
    Show the answer and explanation

    Answer: B. A free slot is a slot nobody holds, so it can be worked out from the data you already have. A separate table or flag is tempting because it is easy to read, but it must be kept in step with every booking and cancellation, and the two copies can drift apart.

  2. 2.Where does the foreign key go in a one-to-many relationship between clinicians and slots?
    Show the answer and explanation

    Answer: B. The 'many' side stores one id that points to its single 'one'. A clinicians table cannot hold a variable-length list in one column, which is why putting it there is tempting but breaks the table's shape.

  3. 3.Why does Tidewell enforce 'one live booking per slot' in the database and not only in code?
    Show the answer and explanation

    Answer: B. Code can check, but two requests can both pass the check before either writes. The database applies the rule at the moment of writing. Speed is not the reason, and the 'code cannot check' option is false, but code alone is not enough for a rule that must never break.

Frequently asked questions

What is the difference between an entity and a table?

An entity is the idea: a kind of thing you keep records about, such as a patient. A table is how a relational database stores that idea, with one row per patient and one column per fact. You think in entities first, then build tables.

What is a foreign key in simple terms?

It is a column that holds the id of a record in another table. A booking stores the id of its slot, the way a loan slip stores a library card number. The database refuses an id that does not exist, so links cannot point at nothing.

When do I need a many-to-many relationship?

Use it when each record on both sides can link to several on the other, such as students and courses. You store it with a third table that has one row per pair. If one side only ever links to one record, a plain foreign key is enough.

Can an AI assistant design my database for me?

It can draft one quickly, and it is good at spotting missing links. It cannot know your business rules, and it often adds tables you did not ask for. Use the draft as a starting point, trace each table to a requirement and confirm the rules with the person who owns them.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

  • Constraints(opens in a new tab)

    PostgreSQL Global Development Group · Official documentation · The official guide to NOT NULL, UNIQUE, CHECK and foreign key constraints.

  • Partial Indexes(opens in a new tab)

    PostgreSQL Global Development Group · Official documentation · Explains indexes that cover only some rows, the tool behind the one-live-booking rule.

  • Date/Time Types(opens in a new tab)

    PostgreSQL Global Development Group · Official documentation · Why moments in time are stored as timestamp with time zone.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.