Courses / Databases for Backend Interviews / Chapter 4
Module 3 · Data modelling and the ER model · Chapter 4 of 27
Data Modelling: From Requirements to Conceptual, Logical and Physical Models
Builds on Databases and the DBMS: Catalogues, Schemas and Data Independence. Next up: The Entity-Relationship Model: Entities, Relationships, Cardinality and Mapping.
Part 1 · What a data model is
A model is a plan for the data
Before you create a table you decide what the data is, how it connects and what it must never contain. That decision is a data model, and this chapter builds one for a clinic in Pune.
A data model is a description of the data an application keeps: the things it tracks, how they relate and which rules hold. A schema is that description written down for a particular DBMS. The model is the thinking and the schema is the result.
Modelling is done in layers, because different people need different amounts of detail. A clinic manager can say "a patient books an appointment with a doctor" and knows nothing about column types. A DBA has to choose those types and the indexes. If both talk about the same picture, one of them is lost.
Here is one fact from the clinic written at each of the three levels that the next page defines. The fact does not change. Only the amount of engine detail does.
| Level | The same fact |
|---|---|
| Conceptual | A patient books an appointment with a doctor |
| Logical | appointments (appointment_id key, doctor_id refers to doctors, patient_id refers to patients, starts_at) |
| Physical | appointment_id bigint identity primary key; doctor_id int NOT NULL references doctors; starts_at timestamptz NOT NULL; an index on (patient_id, starts_at) |
Conceptual, logical and physical
| Level | Describes | Typical contents | Read by |
|---|---|---|---|
| Conceptual | The business in plain terms | Entities, relationships, key rules; no types, no keys | Domain experts, product owners, designers |
| Logical | The structure of the data, free of engine detail | Tables, columns, primary and foreign keys, normalised design | Designers, developers |
| Physical | The schema for one engine | Data types, NOT NULL, CHECK, defaults, indexes, partitioning | Developers, DBAs |
DescribesThe business in plain terms
Typical contentsEntities, relationships, key rules; no types, no keys
Read byDomain experts, product owners, designers
DescribesThe structure of the data, free of engine detail
Typical contentsTables, columns, primary and foreign keys, normalised design
Read byDesigners, developers
DescribesThe schema for one engine
The smallest physical model
The quickest way to see where all three levels end up is to build the smallest possible version. This table keeps every fact as free text, in one place. It runs, and it answers a question.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE appointments ( patient text, doctor text, at text ); INSERT INTO appointments (patient, doctor, at) VALUES ('Kavya Rao', 'Dr Iyer', '2026-12-01 10:00'), ('Rohan Das', 'Dr Iyer', '2026-12-01 10:15'), ('Kavya Rao', 'Dr Menon', '2026-12-02 09:30'); `) show((await db.query( 'SELECT doctor, count(*) AS visits FROM appointments ' + 'GROUP BY doctor ORDER BY doctor')).rows)
doctor | visits ---------+------- Dr Iyer | 2 Dr Menon | 1 (2 rows)
It also has problems you can already see. A doctor is a piece of text, so "Dr Iyer" and "Dr. Iyer" count as two doctors. A time is a piece of text too, so the engine cannot add a day to it or reject a date that does not exist. Nothing says a patient exists or that a doctor cannot be in two places at 10:00. The rest of the chapter fixes these in order: first find what the clinic needs, then give each fact a place, then give each place a type and a rule.
What is the difference between a data model and a schema?
- The model is the description of the data: things, relationships and rules. The schema is that description written for a particular DBMS.
Which level contains data types and indexes?
- The physical level. The conceptual level has neither, and the logical level uses only rough types, if any.
Why does the one-table version count "Dr Iyer" and "Dr. Iyer" as different doctors?
- The doctor is only text, so the engine compares characters. Nothing links the name to a single stored doctor.
Part 2 · Reading requirements
From sentences to a model
Requirements arrive as sentences. The clinic group writes: "Each doctor has a speciality. A patient books an appointment with one doctor at a time slot. A doctor cannot be booked twice at the same time. Reception must see a doctor's day, and a patient's history. Fees are in rupees and cannot be negative."
You can read a model out of text like this with a few habits. They are rules of thumb, not laws.
| Look for | It usually becomes | In the clinic text |
|---|---|---|
| A noun the business keeps facts about | An entity (later a table) | doctor, patient, appointment |
| A noun that only describes another | An attribute (later a column) | speciality, time slot, fee |
| A verb linking two nouns | A relationship | a patient books an appointment with a doctor |
| "must", "cannot", "only", "at most" | A constraint | not booked twice, fee not negative |
| A question that someone will ask | An access pattern | a doctor's day, a patient's history |
An access pattern is a question the application asks of the data, with its shape: which key it filters by and how often. Access patterns matter because they decide the indexes later, and in NoSQL stores they decide the whole design.
Also ask what the text leaves out. Can one appointment have two doctors? Can an appointment be cancelled, and is it then still in the history? Each answer you write down is a rule. Each answer you do not get is a risk.
Turning a rule into a constraint
Take the rule "a doctor cannot be booked twice at the same time". The first way to enforce it is a unique constraint: no two rows may hold the same values in the listed columns. The script below puts it on (doctor_id, starts_at), and tries three inserts.
import { PGlite } from '@electric-sql/pglite' import { btree_gist } from '@electric-sql/pglite/contrib/btree_gist' import { show } from '../show.ts' const db = new PGlite({ extensions: { btree_gist } }) await db.exec("SET TIME ZONE 'Asia/Kolkata'") await db.exec(` CREATE EXTENSION btree_gist; CREATE TABLE slots ( doctor_id int NOT NULL, starts_at timestamptz NOT NULL, UNIQUE (doctor_id, starts_at) ); INSERT INTO slots (doctor_id, starts_at) VALUES (1, '2026-12-01 10:00+05:30'); `) async function attempt(label: string, sql: string, params: unknown[]) { try { await db.query(sql, params) console.log(`${label}: accepted`) } catch (e) { const err = e as { code: string; constraint: string } console.log(`${label}: rejected ${err.code} ${err.constraint}`) } }
const slot = 'INSERT INTO slots (doctor_id, starts_at) VALUES ($1, $2)' await attempt('same doctor, same time', slot, [1, '2026-12-01 10:00+05:30']) await attempt('other doctor, same time', slot, [2, '2026-12-01 10:00+05:30']) await attempt('same doctor, 10:05', slot, [1, '2026-12-01 10:05+05:30']) // Overlap needs a range and an exclusion constraint. await db.exec(` CREATE TABLE bookings ( doctor_id int NOT NULL, during tstzrange NOT NULL, EXCLUDE USING gist (doctor_id WITH =, during WITH &&) ); INSERT INTO bookings (doctor_id, during) VALUES (1, tstzrange('2026-12-01 10:00+05:30', '2026-12-01 10:15+05:30')); `) const book = `INSERT INTO bookings (doctor_id, during) VALUES ($1, tstzrange($2, $3))` await attempt('overlapping booking', book, [1, '2026-12-01 10:10+05:30', '2026-12-01 10:25+05:30']) await attempt('back-to-back booking', book, [1, '2026-12-01 10:15+05:30', '2026-12-01 10:30+05:30']) show((await db.query( 'SELECT doctor_id, during FROM bookings ORDER BY during')).rows)
same doctor, same time: rejected 23505 slots_doctor_id_starts_at_key other doctor, same time: accepted same doctor, 10:05: accepted overlapping booking: rejected 23P01 bookings_doctor_id_during_excl back-to-back booking: accepted doctor_id | during ----------+---------------------------------------------------------- 1 | ["2026-12-01 10:00:00+05:30","2026-12-01 10:15:00+05:30") 1 | ["2026-12-01 10:15:00+05:30","2026-12-01 10:30:00+05:30") (2 rows)
The first attempt, the same doctor at the same time, is refused with SQLSTATE 23505, the code for a unique violation. A different doctor at the same time is accepted, which is right. The same doctor five minutes later is also accepted, and that is a gap: a 15-minute appointment at 10:00 and another at 10:05 overlap, and a unique constraint on the start time does not see it.
When equal is not enough
The second half of the script fixes the gap. It stores each booking as a tstzrange, a range of timestamps with time zone, and adds an exclusion constraint: no two rows may have the same doctor and overlapping ranges. The && operator means "overlaps". The constraint needs the btree_gist extension to compare the doctor with = inside a GiST index.
The overlapping booking from 10:10 to 10:25 is refused with 23P01, the code for an exclusion violation. The booking that starts at 10:15, exactly when the first one ends, is accepted, because a range written as [start, end) includes its start and excludes its end. That convention lets back-to-back slots sit side by side.
Two points about the output. The two instants are printed in Indian time because the script sets the session time zone to Asia/Kolkata. And the constraint belongs in the database, not only in the booking screen. A screen can check for a clash, but two receptionists can book the same slot in the same second, and only a constraint inside the DBMS can stop both.
Which words in a requirement usually signal a constraint?
- Words such as must, cannot, only and at most.
Why was the booking at 10:05 accepted by the unique constraint, and what catches it?
- The constraint compares start times for equality, and 10:05 differs from 10:00. An exclusion constraint on a time range detects the overlap.
What is an access pattern and why record it during modelling?
- A question the application asks, with the key it uses. It tells you which indexes to build, and in NoSQL stores which keys to design around.
Part 3 · The logical model
Tables, keys and relationships
The logical model turns each entity into a table, each attribute into a column and each relationship into a foreign key. It uses keys but not yet fine detail about types.
A primary key is a column, or set of columns, whose value identifies one row and is never null. A foreign key is a column whose values must match a primary key in another table. It is how one row refers to another: the doctor_id in an appointment points at one row in doctors.
From the clinic text you get three entities and two relationships. A doctor has many appointments. A patient has many appointments. An appointment belongs to exactly one doctor and one patient, so the foreign keys live in the appointments table, on the "many" side. The appointment is therefore the table that connects the other two.
| Table | Primary key | Foreign keys | Other columns |
|---|---|---|---|
| doctors | doctor_id | none | name, speciality |
| patients | patient_id | none | name, phone |
| appointments | appointment_id | doctor_id, patient_id | starts_at |
Primary keydoctor_id
Foreign keysnone
The same model as DDL
DDL, data definition language, is the part of SQL that creates and changes structure. This script writes the logical model as DDL with keys only: the types are rough, and there are no checks or defaults yet. A query on the catalogue then lists the foreign keys that PostgreSQL recorded.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() // Logical model: tables, keys and relationships. Types are rough. await db.exec(` CREATE TABLE doctors ( doctor_id int PRIMARY KEY, name text, speciality text ); CREATE TABLE patients ( patient_id int PRIMARY KEY, name text, phone text ); CREATE TABLE appointments ( appointment_id int PRIMARY KEY, doctor_id int REFERENCES doctors, patient_id int REFERENCES patients, starts_at timestamptz ); `) show((await db.query(` SELECT conrelid::regclass AS from_table, confrelid::regclass AS to_table, conname FROM pg_constraint WHERE contype = 'f' ORDER BY conname`)).rows)
from_table | to_table | conname
-------------+----------+-----------------------------
appointments | doctors | appointments_doctor_id_fkey
appointments | patients | appointments_patient_id_fkey
(2 rows)REFERENCES doctors with no column named means "the primary key of doctors". PostgreSQL named the two foreign keys itself. Each row of the output is one relationship of the model.
What the logical level leaves open
A logical model can be checked for design quality before any engine is chosen. The question to ask is whether each fact is stored once. The doctor name is in the doctors table and nowhere else, so renaming a doctor changes one row. The same idea, called normalisation, gets a full treatment in a later chapter.
Three checks catch most logical mistakes. First, ask of every table what identifies one row; a table with no answer needs a key. Second, ask of every non-key column which key it describes. A speciality describes a doctor, so it belongs in doctors, and putting it in appointments would repeat it on every visit. Third, read each foreign key aloud in both directions: an appointment has one doctor, and a doctor has many appointments. If either sentence is wrong for the clinic, the relationship is wrong, and the foreign key is probably on the wrong table.
A related choice is what the key should be. A natural key is a value the business already uses, such as a phone number. A surrogate key is a number the database makes up, such as patient_id. The phone looks tempting, but a key must be unique and should not change, and the phone fails both: two members of one family may share a phone, and a patient may change it. A key that changes forces every foreign key that copies it to change too. The clinic model therefore uses surrogate keys and keeps the phone as an ordinary column.
The model also leaves open decisions that depend on the DBMS. Should the key be a small integer or a UUID? Should the time carry a time zone? How long can a name be? These belong to the next level.
Where does the foreign key go in a one-to-many relationship?
- On the many side. Each appointment holds the doctor_id of its one doctor.
A colleague adds a speciality column to appointments so that the doctor's day screen needs no join. What goes wrong?
- The speciality describes the doctor, not the visit, so it is repeated on every appointment of that doctor.
- When a speciality changes, every copy must change, and a missed copy makes the data disagree with itself. It belongs in doctors.
Part 4 · The physical model
Types, constraints and defaults
The physical model chooses, for PostgreSQL, how each column is stored and which rules the engine enforces. Each choice has a reason.
| Column | Choice | Reason |
|---|---|---|
| doctor_id, patient_id | int, identity | Four bytes, values up to 2,147,483,647 (about 214 crore); the DBMS hands out the numbers |
| appointment_id | bigint, identity | This table grows fastest, so it gets the larger key |
| starts_at | timestamptz | Stores an instant; PostgreSQL keeps it in UTC and shows it in the session time zone |
| duration_min | smallint with CHECK 5 to 120 | Small values; a rule against nonsense |
| status | text with CHECK in a list | Three allowed values; the default is booked |
| fee | numeric(8,2) with CHECK of 0 or more | Exact decimals for money, never floating point |
NOT NULL is the first constraint to reach for. A column that may be missing needs an explicit reason, as the patient phone has. An identity column (GENERATED ALWAYS AS IDENTITY) has the DBMS assign increasing numbers. A default fills a column when an insert leaves it out.
The clinic schema
This is the physical schema that the rest of the lesson measures. It adds the unique constraint from the requirements and one index for the patient history.
CREATE TABLE doctors ( doctor_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, speciality text NOT NULL ); CREATE TABLE patients ( patient_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, phone text ); CREATE TABLE appointments ( appointment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, doctor_id int NOT NULL REFERENCES doctors, patient_id int NOT NULL REFERENCES patients, starts_at timestamptz NOT NULL, duration_min smallint NOT NULL DEFAULT 15 CHECK (duration_min BETWEEN 5 AND 120), status text NOT NULL DEFAULT 'booked' CHECK (status IN ('booked', 'done', 'cancelled')), fee numeric(8,2) NOT NULL DEFAULT 0 CHECK (fee >= 0), UNIQUE (doctor_id, starts_at) ); CREATE INDEX appointments_patient_idx ON appointments (patient_id, starts_at);
PostgreSQL builds an index for every primary key and unique constraint, so the table already has two. It does not build an index for a foreign key. The index appointments_patient_idx answers "a patient history" and is listed by its columns, patient first and then time, so rows for one patient come out in time order. The doctor's day is served by the index behind the unique constraint, whose first column is the doctor.
Sizing a table with real numbers
Types decide how much space a row takes, and space turns into disk, memory and time. The script loads 1 lakh appointments, then measures. pg_column_size returns the bytes a stored value occupies. pg_relation_size returns the size of a table or index in bytes.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' import { ddl } from './ddl.ts' const db = new PGlite() await db.exec(ddl) await db.exec(` INSERT INTO doctors (name, speciality) SELECT 'Doctor ' || n, 'General' FROM generate_series(1, 30) AS n; INSERT INTO patients (name, phone) SELECT 'Patient ' || n, '09000' || lpad(n::text, 5, '0') FROM generate_series(1, 5000) AS n; INSERT INTO appointments (doctor_id, patient_id, starts_at, fee) SELECT 1 + n % 30, 1 + n % 5000, timestamptz '2026-01-01 09:00+05:30' + n * interval '1 minute', 300 FROM generate_series(1, 100000) AS n; `)
console.log('-- average bytes per column value, from the table itself') show((await db.query(` SELECT avg(pg_column_size(appointment_id))::numeric(4,1) AS id, avg(pg_column_size(doctor_id))::numeric(4,1) AS doctor, avg(pg_column_size(patient_id))::numeric(4,1) AS patient, avg(pg_column_size(starts_at))::numeric(4,1) AS starts, avg(pg_column_size(duration_min))::numeric(4,1) AS minutes, avg(pg_column_size(status))::numeric(4,1) AS status, avg(pg_column_size(fee))::numeric(4,1) AS fee FROM appointments`)).rows) console.log('-- the whole table on disk') show((await db.query(` SELECT count(*) AS row_count, pg_relation_size('appointments') AS heap_bytes, pg_relation_size('appointments') / count(*) AS per_row FROM appointments`)).rows) console.log('-- the three indexes, bytes per row') show((await db.query(` SELECT indexrelid::regclass AS index_name, pg_relation_size(indexrelid) AS bytes, pg_relation_size(indexrelid) / 100000 AS per_row FROM pg_index WHERE indrelid = 'appointments'::regclass ORDER BY indexrelid::regclass::text`)).rows)
-- average bytes per column value, from the table itself id | doctor | patient | starts | minutes | status | fee ----+--------+---------+--------+---------+--------+---- 8.0 | 4.0 | 4.0 | 8.0 | 2.0 | 7.0 | 5.0 (1 row) -- the whole table on disk row_count | heap_bytes | per_row ----------+------------+-------- 100000 | 6832128 | 68 (1 row) -- the three indexes, bytes per row index_name | bytes | per_row -------------------------------------+---------+-------- appointments_doctor_id_starts_at_key | 3268608 | 32 appointments_patient_idx | 4431872 | 44 appointments_pkey | 2260992 | 22 (3 rows)
Sizes are exact for this data; yours match if you run the same script.
Where the other 30 bytes go
To see where the other 30 bytes go, the pageinspect extension reads one 8 KB page of the table directly. lp_len is the stored length of a row, t_hoff the size of its header, and lp_off where the row starts in the page. lower and upper are the ends of the free space in the middle of the page.
import { PGlite } from '@electric-sql/pglite' import { pageinspect } from '@electric-sql/pglite/contrib/pageinspect' import { show } from '../show.ts' import { ddl } from './ddl.ts' const db = new PGlite({ extensions: { pageinspect } }) await db.exec(ddl) await db.exec(` CREATE EXTENSION pageinspect; INSERT INTO doctors (name, speciality) VALUES ('Doctor 1', 'General'); INSERT INTO patients (name) VALUES ('Patient 1'); INSERT INTO appointments (doctor_id, patient_id, starts_at, fee) SELECT 1, 1, timestamptz '2026-01-01 09:00+05:30' + n * interval '15 minutes', 300 FROM generate_series(1, 200) AS n; `) console.log('-- the first three rows of page 0') show((await db.query(` SELECT lp, lp_off, lp_len, t_hoff FROM heap_page_items(get_raw_page('appointments', 0)) WHERE lp <= 3 ORDER BY lp`)).rows) console.log('-- page 0 as a whole') show((await db.query(` SELECT count(*) AS rows_on_page FROM heap_page_items(get_raw_page('appointments', 0))`)).rows) show((await db.query(` SELECT lower, upper, pagesize FROM page_header(get_raw_page('appointments', 0))`)).rows)
-- the first three rows of page 0 lp | lp_off | lp_len | t_hoff ---+--------+--------+------- 1 | 8128 | 62 | 24 2 | 8064 | 62 | 24 3 | 8000 | 62 | 24 (3 rows) -- page 0 as a whole rows_on_page ------------ 120 (1 row) lower | upper | pagesize ------+-------+--------- 504 | 512 | 8192 (1 row)
The same row shape as in the sizing run, on a smaller table.
| Bytes | What they are | Seen in the run |
|---|---|---|
| 24 | Row header: 23 bytes, padded so the values start on an aligned boundary | t_hoff = 24 |
| 38 | The seven values | lp_len = 62 = 24 + 38 |
| 2 | Padding so the next row also starts on an aligned boundary |
From a row to years of data
Storage for five years: ≈ 180 MB (about 36 MB a year, from measured sizes)
Read it as steps
Bytes per row from a real run, times rows per year.
The scene applies those numbers to five clinics with six doctors each, 30 in all. One year is about 2.16 lakh rows and 36 MB, and five years about 180 MB, small for a modern server. The point of the sum is the method: bytes per row from a measurement, rows from the business, a product at the end that you can compare with disk or memory.
Why was the table 68 bytes per row when the values add up to 38?
- Each row also has a 24-byte header (23 bytes plus padding), 2 bytes of padding after the values and a 4-byte line pointer: 30 bytes.
- The page header is shared by the 120 rows on each page, so it adds less than one byte per row.
Does PostgreSQL create an index for a foreign key column?
- No. It creates indexes for primary keys and unique constraints. A foreign key column such as patient_id needs an index you create yourself.
Why store fee as numeric(8,2) and not as a floating-point type?
- numeric is exact, so rupees and paise are never rounded in the binary representation, which matters for money.
Part 5 · Other data models in one page
Five ways to organise data
A data model in the older, narrower sense is a family of rules for how data is structured. The clinic schema uses the relational model. It is not the only one.
| Model | Shape | Linking records | Typical today |
|---|---|---|---|
| Hierarchical | A tree of parent and child records | A child has one parent; you navigate from the root | Legacy mainframe systems; XML and file trees |
| Network | A graph of records joined by links | A record can have several parents; you follow links | Legacy systems, such as CODASYL databases |
| Relational | Tables of rows | Foreign keys matched by queries | PostgreSQL, MySQL, SQLite |
| Document | Nested JSON-like documents | Embed related data, or store ids | MongoDB, JSON columns |
| Graph | Nodes and edges, both with properties | Edges are stored and traversed | Neo4j, relationship-heavy data |
ShapeA tree of parent and child records
Linking recordsA child has one parent; you navigate from the root
Rows against documents
The same visits can be stored both ways in PostgreSQL. The script keeps a visits table with a foreign key to patients, and a visit_docs table in which each visit is a jsonb document with the patient embedded. The operator @> tests whether a document contains a given piece of JSON.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE patients (patient_id int PRIMARY KEY, name text); CREATE TABLE visits ( visit_id int PRIMARY KEY, patient_id int NOT NULL REFERENCES patients, doctor text, note text ); INSERT INTO patients (patient_id, name) VALUES (1, 'Kavya Rao'), (2, 'Rohan Das'); INSERT INTO visits (visit_id, patient_id, doctor, note) VALUES (1, 1, 'Dr Iyer', 'fever'), (2, 1, 'Dr Menon', 'cough'), (3, 2, 'Dr Iyer', 'checkup'); CREATE TABLE visit_docs (id int PRIMARY KEY, doc jsonb); INSERT INTO visit_docs (id, doc) VALUES (1, '{"patient": {"id": 1, "name": "Kavya Rao"}, "doctor": "Dr Iyer", "note": "fever"}'), (2, '{"patient": {"id": 1, "name": "Kavya Rao"}, "doctor": "Dr Menon", "note": "cough"}'), (3, '{"patient": {"id": 2, "name": "Rohan Das"}, "doctor": "Dr Iyer", "note": "checkup"}'); `)
console.log('-- rows: visits of one patient') show((await db.query(` SELECT v.visit_id, v.doctor, v.note FROM visits v JOIN patients p USING (patient_id) WHERE p.name = 'Kavya Rao' ORDER BY v.visit_id`)).rows) console.log('-- document: the same question') show((await db.query(` SELECT id, doc->>'doctor' AS doctor, doc->>'note' AS note FROM visit_docs WHERE doc @> '{"patient": {"name": "Kavya Rao"}}' ORDER BY id`)).rows) // Kavya changes her name: one row against every document. await db.query('UPDATE patients SET name = $1 WHERE patient_id = $2', ['Kavya Rao-Nair', 1]) const fix = await db.query(` UPDATE visit_docs SET doc = jsonb_set(doc, '{patient,name}', '"Kavya Rao-Nair"') WHERE doc @> '{"patient": {"id": 1}}'`) const n = fix.affectedRows console.log(`one patient row changed, ${n} documents changed`)
// A visit for a patient who does not exist, stored both ways. try { await db.query(`INSERT INTO visits (visit_id, patient_id, doctor) VALUES (4, 99, 'Dr Iyer')`) } catch (e) { console.log(`row: rejected ${(e as { code: string }).code}`) } await db.query(`INSERT INTO visit_docs (id, doc) VALUES (4, '{"patient": {"id": 99}, "doctor": "Dr Iyer"}')`) console.log('document: accepted')
-- rows: visits of one patient visit_id | doctor | note ---------+----------+------ 1 | Dr Iyer | fever 2 | Dr Menon | cough (2 rows) -- document: the same question id | doctor | note ---+----------+------ 1 | Dr Iyer | fever 2 | Dr Menon | cough (2 rows) one patient row changed, 2 documents changed row: rejected 23503 document: accepted
Why the choice follows access patterns
Documents are not worse. If the application always loads a visit together with the patient name as it was at the time, then a copy is a feature, not a flaw: the receipt of that visit should not change when the patient is later renamed. The embedded copy also saves a join when the application reads one visit.
So the choice depends on the questions you wrote down while reading the requirements. If many different questions cross the same facts, relational tables keep each fact once and let any query join them. If one question dominates and the data fits inside one record, a document can answer it with one read. A later chapter returns to this and designs from the access patterns first.
| Term | Meaning |
|---|---|
| Data model | A description of the data an application keeps: its things, relationships and rules |
| Conceptual model | The business view: entities and relationships, no types |
| Logical model | Tables, columns and keys, independent of an engine |
| Physical model | The schema for one DBMS: types, constraints, indexes |
| Access pattern | A question the application asks of the data, with the key it uses |
| Exclusion constraint | A rule that no two rows may conflict under given operators, such as overlapping ranges |
In the run, how many rows and how many documents changed when a patient was renamed?
- One row in patients and two documents in visit_docs.
Give one case where copying the patient name into the visit is correct.
All chapters · Previous: Databases and the DBMS: Catalogues, Schemas and Data Independence