Chapter 15 — Relational Foundations: the Model, SQL, Keys, Constraints, Joins
Part IV · Data & Storage | Prerequisites: Ch 1 | Builds: Pulsely's first SQL schema and queries
Earlier we drew the spine and put a single box at the end of it: the database. We called it "durable state" and "the single source of truth," and then — deliberately — we left it shut. Every chapter since has been about getting a request to that box safely: the runtime that runs your handler, the contract the API presents, the dependency wiring that holds it together. Now we open the box. Part IV is the deepest part of this book because it is where "the truth" actually lives, and a backend engineer who is fuzzy about how truth is stored is fuzzy about everything that depends on it — which is everything. In a healthcare system that weight is literal: the box holds who a patient is, what was charted, which claim was paid, and who is allowed to look.
This first chapter is about the relational model: the single most successful idea in the history of data storage, and one that most developers use daily while understanding almost none of it. You write SELECT queries the way you'd cast a spell — say the words, get the rows — without knowing why the words work. By the end of this chapter you'll be able to derive the relational model from set theory, explain why a constraint declared in the schema is worth more than a thousand lines of careful validation code, read the four-plus-two join shapes off a Venn diagram, and write set-based SQL that thinks the way the engine thinks. We'll author Pulsely's first real schema along the way. This is a concept-dense chapter that earns the SQL you'll lean on for the rest of the book — slow down and let the model click, because every later chapter (modeling, transactions, storage internals, Postgres) is a zoom-in on a box you're about to draw.
1. The problem: why the relational model exists at all
Let me start where almost every backend engineer's database education actually starts: with a bug that no amount of careful code can fix, because the bug isn't in the code.
Pulsely needs unique medical record numbers. Two charts can't exist for the same MRN — that's a split chart, the most dangerous data-integrity failure in an EHR, because a clinician looking at one half can't see the allergy or the medication recorded on the other. The obvious implementation — the one that looks correct, passes review, and ships — is check, then insert:
// Looks airtight. Is not.
const existing = await db.query('SELECT id FROM patients WHERE mrn = $1', [mrn]);
if (existing.rows.length > 0) {
throw new ConflictError('patient already registered');
}
await db.query('INSERT INTO patients (mrn, ...) VALUES ($1, ...)', [mrn, ...]);
In development, where you are the only user clicking one button at a time, this is flawless. In production, two front-desk staff register the same returning patient — MRN MRN-4471 — inside the same 30-millisecond window. Request A runs the SELECT — zero rows, the MRN is free. Request B runs its SELECT — also zero rows, because A hasn't inserted yet. Both checks pass. Both inserts run. You now have two patient records under MRN-4471, and every "find the patient by MRN" query for the rest of that chart's life returns an ambiguous result — the split chart. The check passed for both before either committed. No retry, no try/catch, no more careful JavaScript fixes this, because the correctness was placed in the wrong layer. The check and the write were two separate trips across the network with a gap in between, and the second writer slipped into the gap.
Here is the lesson, and it is the thesis of this entire chapter: a rule enforced by the code that happens to write the data is not enforced at all, because there is always another writer. The fix is one line, and it lives in the database, not the app:
ALTER TABLE patients ADD CONSTRAINT patients_mrn_key UNIQUE (mrn);
With that constraint, the second INSERT doesn't check — it fails, atomically, decided by the engine at the moment of write. There is no gap to slip into, because uniqueness is now a property the data physically cannot violate, no matter who writes it or how many of them write at once.
The same one-line move guards a different Pulsely invariant: two front-desk staff must never book the same 9:00 slot with the same provider. A UNIQUE (provider_id, starts_at) on appointment_slots makes the second booking fail instead of check — the no-double-booking rule becomes a property the data physically cannot violate. (Holding a slot while a longer intake workflow runs needs locking, which is Chapter 17's job; the constraint is the floor beneath it.)
Now widen the lens, because uniqueness is just the first symptom. Picture the other failure this chapter exists to prevent: the spreadsheet that grew into a database. A patient's name is recorded Ada Lovelace, ada lovelace, and A. Lovelace across three separate charts, because nothing forced it to be one value. A claims row has a provider column that is sometimes an NPI, sometimes a name, sometimes blank. A claim points at an encounter that was voided last week, so the claim-detail page 500s and billing can't reconcile the remittance. None of this is a crash in the code. It's data the application assumed was consistent and nothing guaranteed. The app that wrote it believed its own rules. The migration script that ran at 2 a.m. didn't know those rules. The analyst running ad-hoc psql certainly didn't. Every writer reinvented the invariants, inconsistently, and the data rotted in the gaps between their assumptions.
🚫 A framing this book rejects. "The database is just where we persist our objects; the real rules live in the application." This is the seductive ORM-era view, and it's exactly backwards. The application is one writer among many — your other services, your migrations, your cron jobs, the background worker ingesting RPM device readings, the nightly claims batch, the panicked manual fix during an incident, the next team that integrates a lab feed. A rule that lives only in the app is a rule that every other writer is free to violate. The database is the one place every writer must pass through. Putting correctness there isn't pedantry; it's the only place it actually holds.
You might ask: couldn't a key-value store or a pile of JSON blobs do this? No — and the reasons are instructive. A KV store has no engine-level concept of "this field must reference a real, existing row," so referential integrity is back to being your app's problem (and your app has a gap). It has no declarative way to ask "which patients have zero submitted claims" without dragging every record into application memory and looping. And it forces every invariant to be re-implemented in every service that touches the data, which means re-implemented inconsistently. The relational model exists to make a different promise: correctness is a property of the data, not of the code that happens to write it. Multiple apps, scripts, and humans can hammer the same database, and the engine still refuses to enter a bad state. The payoff is two-sided — declarative, set-based queries replace your hand-written loops, and the engine becomes the single enforcement point for invariants that would otherwise be scattered and racy. That's the deal. The rest of this chapter is the fine print.
2. The mental model: tables are sets, queries are functions
Most developers carry a mental picture of a database table as a spreadsheet: a grid you scroll through, rows in the order you typed them, columns you can point at by position. That picture is comfortable and it is wrong in three ways that will bite you. Replace it with the picture the relational model is actually built on.
A table is a relation: an unordered set of rows over a fixed header. The word "set" is load-bearing, so press on it. A set has no duplicates — a true relation cannot contain the same row twice. A set has no inherent order — there is no "first row," and the order you get back from a query is undefined unless you ask for one. A set has no positional access — you never reach for "column 3," you reach for the column named mrn. Internalize this and a whole category of bugs evaporates before you write them. The day you rely on "the rows come back in insertion order," you've written a bug that works on your laptop and fails the moment the engine picks a different plan in production.
A row is a tuple: a mapping from attribute name to value. Not a positional list — a named mapping. { id: 7, mrn: 'MRN-4471', full_name: 'Ada Lovelace', ... }. You address mrn by its name, forever, regardless of where it sits in the CREATE TABLE. This is why adding a column doesn't break a query that names its columns, and why SELECT * (which secretly depends on position and presence) is fragile.
A query is a function from relations to a relation. This is the idea that unlocks SQL. SELECT, JOIN, WHERE, GROUP BY — each takes one or more tables in and returns a table out. That's why queries compose: because the output of a query is itself a relation, you can feed it into another query (a subquery, a CTE, a join). You are not writing a procedure that mutates state step by step; you are composing functions over sets.
🧭 Mental model. You are not telling the database how to get the rows. You are describing the set of rows you want and letting the engine figure out how. This is the single biggest shift for someone arriving from application code, where you're used to writing the loop yourself —
for (const row of rows) { if (...) results.push(row) }. In SQL you state the predicate (WHERE status = 'submitted') and the engine writes the loop, picks the strategy, uses an index if one helps, and parallelizes if it can. Declare the what; surrender the how. Fighting this — pulling rows into the app to filter them in aforloop — is the most common and most expensive mistake a backend dev makes against a database.
Two more pieces complete the model, and both reframe things you already half-know.
Constraints are predicates the engine promises will always be true. Think of every constraint — NOT NULL, UNIQUE, CHECK, FOREIGN KEY — as an invariant the database will never let you violate, checked on every single write, forever, regardless of which client did the writing. A CHECK (charge_amount_cents >= 0) isn't documentation; it's a law of physics for that column. The engine will reject, with an error, any transaction that would leave the data in a state where the predicate is false.
A schema is a type system for your data at rest. You already trust TypeScript to reject const x: number = "hello" at compile time. A schema does the same thing for your stored data, except it's enforced at runtime, on every write, by the engine — which is strictly stronger, because TypeScript's guarantees evaporate at the network boundary (we'll see exactly where, in §4). Keys and constraints are the type annotations the database actually enforces, against every writer, including the ones you didn't write.
3. Theory & invariants
A mental model tells you how to picture the relational world. The theory tells you why it's coherent — and the relational model is one of the rare places in software engineering where the theory is genuinely beautiful, genuinely useful, and only takes twenty minutes to absorb. We'll derive the load-bearing rules, because rules you derive you keep, and rules you memorize you forget on the day you need them.
Relations as applied set theory
Start from domains. A domain is a typed set of allowed values: INTEGER is the domain of integers, TEXT the domain of strings, BOOLEAN the domain {true, false}. Every attribute (column) draws from exactly one domain, and this is your first line of correctness — you physically cannot put a string where an INTEGER domain is declared; the engine rejects it before any of your logic runs.
Now the formal definition. It sounds abstract for one sentence and then pays off forever, so let me give you the picture before the term. Imagine every possible integer paired with every possible string: an impossibly huge grid of every combination that could exist. Your actual table is just the handful of those rows you've decided are actually true — the patients who really exist. That huge grid of all possible pairings has a name; mathematicians call it the Cartesian product, and your table is a subset of it — the rows that do exist, carved out of the rows that could.
Now the same idea, formally. A relation is a subset of the Cartesian product of its attributes' domains. If patients has attributes id : INTEGER and mrn : TEXT, then the universe of possible rows is every pairing of an integer with a string — INTEGER × TEXT — and your actual table is some chosen subset of that universe. A tuple (row) is one element of that product: one specific (integer, string) pairing that you've decided is true.
From this single definition, the three "weird" properties of tables fall out for free:
- No duplicate rows — because a relation is a set, and a set cannot contain the same element twice. Duplicate rows aren't forbidden by a rule someone added; they're impossible by the definition of "set."
- No inherent order — because set membership is unordered.
{a, b} = {b, a}. The engine is free to return rows in whatever order is fastest. - Columns addressed by name — because each tuple is a mapping attribute→value, not a positional vector.
🔑 The set invariant. A table is a set of tuples. Therefore: never rely on row order without an explicit
ORDER BY, never rely on a row appearing exactly once unless a key guarantees it, and never address a column by position. Every one of these rules is just "a set has no order and no duplicates" wearing different clothes. When a query that "worked yesterday" returns rows in a new order today, it's not a bug in the engine — it's the engine exercising a freedom the model always gave it, and your code that depended on order being the actual bug.
Keys, precisely
"Primary key" is a phrase everyone uses and few can define. Let's build it from the bottom, because the hierarchy is the whole answer to a common interview question.
- A superkey is any set of attributes that uniquely identifies a tuple.
{id}is a superkey ofpatients. So is{id, mrn}— it identifies uniquely, just with a redundant attribute along for the ride. Superkeys are cheap; most attribute sets that include a unique column are superkeys. - A candidate key is a minimal superkey: remove any attribute and it stops uniquely identifying.
{id}is a candidate key.{mrn}is a candidate key (each MRN belongs to one patient).{id, mrn}is not — it's a superkey but not minimal, because you can dropmrnand{id}still identifies. A table can have several candidate keys. - A primary key is the one candidate key you crown as the official identity. Choosing it has two automatic consequences the engine enforces: the primary key is implicitly
NOT NULL(a thing with no identity can't exist) andUNIQUE(identity that repeats isn't identity). One primary key per table. - A foreign key is an attribute set in one relation whose values must exist as a key in another (or the same) relation.
claims.patient_idis a foreign key referencingpatients.id: every claim must point at a real patient. This is referential integrity — the engine's promise that there are no dangling pointers, no claim floating free of the patient it bills for.
So superkey ⊇ candidate key, and primary key is a chosen candidate key. That's the whole hierarchy, and it's worth being able to draw:
superkeys: {id} {mrn} {id,mrn} {id,created_at} {mrn,full_name} ...
│ │ ↑ has redundant attribute
candidate keys: {id} {mrn} ← minimal superkeys (remove any col, uniqueness breaks)
│
primary key: {id} ← the ONE candidate key you crown
→ implicitly NOT NULL + UNIQUE
Constraints as engine-enforced correctness
The four workhorse constraints are each just a predicate the engine checks on every write. Learn them by what bad state each one makes impossible:
NOT NULL— this attribute must have a value. The domain excludes "unknown." Use it as the default for every column, and treat nullability as a deliberate, justified exception (more in §5).UNIQUE— no two tuples share these values. This is how you declare additional candidate keys beyond the primary key (Pulsely'smrnis unique but isn't the PK). One subtlety that bites people: in standard SQL and Postgres,UNIQUEpermits multiple NULLs, because two unknowns are not provably equal (this is the three-valued logic we're about to meet — NULL is not equal to NULL). SoUNIQUE(mrn)on a nullable column does not stop two rows from both having a NULL MRN.CHECK— an arbitrary row-level predicate that must hold:CHECK (charge_amount_cents >= 0),CHECK (status IN ('draft','submitted','paid','denied')). This is where you encode ranges and enums in the engine instead of trusting the app to do it — and remember, the app is only one of several writers.FOREIGN KEY— referential integrity, plus a declared policy for what happens when the referenced row is deleted. That policy is the referential action:RESTRICT/NO ACTION(refuse to delete the parent while children exist — the safe default),CASCADE(delete the children too — powerful and dangerous), orSET NULL(orphan the children by nulling the link — only valid if the column is nullable). Choosing the action is a real design decision, covered in §5 and §7.
🔑 The constraint invariant. A constraint is enforced on every write from every writer, atomically, inside the database process — not in your app, not "usually," not "when the validation layer remembers." This is why a
UNIQUEconstraint beats an application-level uniqueness check (§1) and aCHECKbeats app validation: the engine is the one writer-agnostic chokepoint every mutation passes through. Push every invariant you can express declaratively into the schema, and you've moved it from "hopefully enforced everywhere" to "provably enforced everywhere."
NULL and three-valued logic
Now the footgun that hides inside the elegance. SQL is not two-valued (TRUE/FALSE) like the booleans you know. It is three-valued: TRUE, FALSE, and UNKNOWN. This exists because of NULL, and NULL is the single most misunderstood value in databases.
NULL does not mean zero. It does not mean empty string. It means "unknown or absent — there is no value here." And the moment you compare against an unknown, the result is itself unknown. Is charge_amount_cents = NULL? You can't know — NULL is "we don't know the charge," and an unknown charge is not provably equal to anything, so the comparison evaluates to UNKNOWN, not TRUE and not FALSE.
This has consequences that will silently drop or leak rows:
-- WHERE keeps only rows where the predicate is TRUE. UNKNOWN is not TRUE.
SELECT * FROM claims WHERE charge_amount_cents = NULL; -- returns ZERO rows, always. NULL = NULL is UNKNOWN.
SELECT * FROM claims WHERE charge_amount_cents IS NULL; -- correct: the special operator for "is it absent?"
SELECT * FROM claims WHERE status != 'denied';
-- SILENTLY DROPS every row where status IS NULL — because NULL != 'denied' is UNKNOWN, not TRUE.
That last one is the quiet killer. A filter that "obviously" should include a row excludes it, because the value it's comparing is NULL and NULL != anything is UNKNOWN. Aggregates have their own NULL behavior too: COUNT(*) counts rows; COUNT(col) counts rows where col is not NULL — they differ exactly by the NULL count, and confusing them produces off-by-N reports (a claims-paid count that quietly ignores the ones with a NULL remittance date).
🔑 The three-valued-logic invariant.
WHEREandHAVINGkeep a row only when the predicate is TRUE — UNKNOWN is discarded along with FALSE. Therefore any comparison that can touch a NULL is suspect: useIS NULL/IS NOT NULLfor presence, useIS DISTINCT FROMfor NULL-safe inequality, and never use=or!=against a column that might be NULL without thinking about the third truth value. This isn't a curiosity for the exam — in §8 you'll see it's a security bug, because a visibility filter that silently drops or leaks NULL rows is, in healthcare, a confidentiality failure.
Normalization, derived from the anomaly each step removes
Normalization is taught as a series of rules to memorize (1NF, 2NF, 3NF, BCNF) and is therefore promptly forgotten. Don't memorize the forms. Derive them from the anomaly each one removes, and you'll re-derive the right design every time. Every normalization step is fixing one of three anomalies:
- Insertion anomaly — you can't record a fact without inventing an unrelated one. ("I can't add a new diagnosis code to the catalog until some claim uses it.")
- Update anomaly — the same fact is stored in N places, so an update must touch all N, and the one you miss becomes a silent inconsistency.
- Deletion anomaly — deleting a row destroys an unrelated fact that happened to live in it. ("I deleted the last claim carrying a diagnosis code and now the code's description is gone.")
Now the ladder, each rung tied to the anomaly it fixes:
- 1NF — atomic values, no repeating groups. No
dx = 'E11.9,I10,Z79.4'crammed into one cell; nodx1, dx2, dx3columns. The anomaly it removes: you can't query inside a cell ("find claims carrying diagnosisI10" becomes a fragileLIKE '%I10%'that also matchesI100andI101), and "which of the three dx columns?" has no good answer. Fix: a value per cell, and repeating groups become child rows in their own table. - 2NF — no partial dependency on part of a composite key. This one only matters when a table's identity is two columns together. Take
encounter_procedures(encounter_id, cpt_code, cpt_description), whose key is the pair(encounter_id, cpt_code). Thecpt_description("Office visit, established patient") depends oncpt_codealone — not on the encounter — so it gets copied onto every row that shares that procedure code. That copying is the anomaly. (If you've worked in React, it's the same smell as duplicating a prop into every child component instead of lifting it to the one place it belongs.) The anomaly: update the description in one row and the copies silently disagree — an update anomaly. Fix: split the columns that depend on only half the key into their own table (here, acpt_codesreference table keyed oncpt_code). - 3NF — no transitive dependency (a non-key attribute depending on another non-key attribute). If
claimsstoredpatient_id, patient_name, patient_dob, thennameanddobdepend onpatient_id, not directly on the claim. The anomaly: correct a patient's name and you must update every claim that carries a copy — miss one row and your data now disagrees with itself. Fix: the patient's details live with the patient, referenced by key. - BCNF — every determinant is a candidate key. A determinant is any column-set whose value forces the value of some other column — if you know the determinant, you know the dependent column. BCNF is the strict form: it requires that every such determinant is itself a candidate key. It closes the residual hole 3NF leaves when candidate keys overlap. For the vast majority of schemas, 3NF and BCNF coincide; BCNF only diverges in unusual cases with multiple overlapping candidate keys. Know it exists; reach for it when 3NF leaves an anomaly standing.
🧭 Mental model for normalization. "Every fact lives in exactly one place." That single sentence is normalization, all the way to BCNF. When a fact is duplicated, you've bought yourself an update anomaly. When a fact can't exist independently, you've bought an insertion or deletion anomaly. Normalize until each fact has one home, and you've removed the whole anomaly family by construction — no memorized rule required.
📎 Borrowed on credit: the modeling discipline. Here we normalize to eliminate anomalies — that's a correctness argument, and it's the right default. But normalization is only half of a larger craft: deciding which facts to model at all (an encounter as an aggregate, a claim as its own lifecycle, code systems as shared reference data), when to deliberately denormalize a hot read path and accept the consistency debt, and how to move from a conceptual picture of the domain down to physical tables. That whole discipline — conceptual → logical → physical, and the denormalization tradeoffs — is Chapter 16. Here, the rule is simple and absolute: normalize for correctness first. Denormalization is an exception you justify later, never a starting point.
Joins as set operations
A join is, mechanically, the Cartesian product of two tables (every left row paired with every right row) filtered by a predicate. You never want the full product; the ON clause is the filter that keeps only the meaningful pairings. The flavors differ only in what they do with rows that find no match:
- INNER JOIN — matched pairs only. A left row with no right match vanishes; a right row with no left match vanishes.
- LEFT OUTER JOIN — keep every left row; for left rows with no right match, NULL-pad the right columns. This is the mechanism by which "no match" becomes a NULL — and the basis of a hugely useful idiom (below).
- RIGHT OUTER JOIN — the mirror image; keep every right row. (Most engineers just flip the table order and use LEFT; RIGHT is rare in practice.)
- FULL OUTER JOIN — keep every row from both sides, NULL-padding whichever side has no match. The union of LEFT and RIGHT.
- SEMI JOIN — not a keyword; you spell it
WHERE EXISTS (...)orWHERE col IN (...). It returns rows of the left table that have at least one match, but adds no columns and never multiplies rows. "Which patients have any claim?" — you want the patient once, not once per claim. - ANTI JOIN — spelled
WHERE NOT EXISTS (...). The complement of a semi join: left rows with no match. This is the correct, NULL-safe tool for "patients with zero claims."
two tables: PATIENTS p CLAIMS c (patient_id → p.id)
[1][2][3] [a→1][b→1][c→2] (patient 3 has no claims)
INNER p⋈c : (1,a)(1,b)(2,c) ← only matched pairs; patient 3 gone
LEFT p⋈c : (1,a)(1,b)(2,c)(3,NULL) ← every patient; patient 3 padded with NULLs
FULL : same as LEFT here (every claim has a patient)
SEMI (EXISTS) : [1][2] ← patients WITH a claim — no row multiply, no extra cols
ANTI (NOT EXISTS): [3] ← patients with NO claim — the "zero claims" query
🔑 The join fan-out invariant. An inner (or left) join on a one-to-many relationship multiplies rows: if patient 1 has three claims, joining
patientstoclaimsproduces three rows for patient 1. Therefore any aggregate (SUM,COUNT) computed after such a join can double-count. If youSUM(patient.outstanding_balance_cents)after joining to claims, you'll sum each patient's balance once per claim and report a number that's wildly too high. This is the single most common silent bug in analytical SQL — "billed charges are mysteriously inflated." The fix is to aggregate before joining, or to use a semi-join when you only need existence. We'll see it bite, and the fix, in §6.
Set-based vs row-by-row
Tie it all together with the mindset shift that separates engineers who use a database from engineers who fight it. Consider "how many submitted claims does each patient have." The application-brain answer is a loop: fetch all patients, then for each patient fire a query counting their claims — N+1 round trips, each a network hop, all serialized, and the count is computed from a moving target as other writers change the data underneath you. The set-based answer is one declarative statement:
SELECT patient_id, COUNT(*) AS submitted_count
FROM claims
WHERE status = 'submitted'
GROUP BY patient_id;
One trip. The engine partitions the set, counts each group, and returns the answer — and it does so over a consistent view of the data (the transaction guarantees of Chapter 17), not a smear of N separately-timed reads. The set-based version is faster, atomic, and lets the engine choose indexes and strategies you'd never hand-code. State the result you want over the whole set; do not iterate. That instinct, more than any syntax, is the fluency this chapter is teaching.
4. Under the hood: SQL as the literal encoding of the model
Now we map every piece of §3 onto real SQL and watch the abstract invariants become syntax you can type. We'll build Pulsely's first schema as we go, and we'll run it against PostgreSQL from Node — the primary lab for this book.
CREATE TABLE: constraints are the model, written down
Here is Pulsely's patients table. Read it not as boilerplate but as a list of §3 invariants encoded in DDL:
CREATE TABLE patients (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- surrogate key; PK ⇒ NOT NULL + UNIQUE
mrn TEXT NOT NULL UNIQUE, -- medical record number: natural candidate key
full_name TEXT NOT NULL,
date_of_birth DATE NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now() -- timezone-aware; defaulted, never null
);
Every line is a promise the engine now keeps for you. PRIMARY KEY makes id the chosen candidate key (auto NOT NULL + UNIQUE). mrn TEXT NOT NULL UNIQUE encodes a second candidate key and forbids absence — the split-chart race from §1 is now structurally impossible. The NOT NULLs mean these columns can never be the "unknown" that breaks your filters in §3.
Now claims, which adds the foreign key — the encoded referential-integrity invariant:
CREATE TABLE claims (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
patient_id BIGINT NOT NULL
REFERENCES patients(id) ON DELETE RESTRICT, -- referential integrity + delete policy
cpt_code TEXT NOT NULL, -- procedure billed (CPT code system)
charge_amount_cents INTEGER NOT NULL CHECK (charge_amount_cents >= 0), -- money as integer minor units
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft','submitted','paid','denied')), -- an enum, enforced
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
patient_id ... REFERENCES patients(id) is the FK: a claim physically cannot point at a non-existent patient. ON DELETE RESTRICT is the declared policy — the engine will refuse to delete a patient who still has claims, rather than silently orphaning the billing record. The two CHECKs encode a range (charge_amount_cents >= 0) and an enum (status IN (...)) directly in the engine, so even a buggy migration or a manual psql UPDATE cannot set a negative charge or an invalid status. Notice charge_amount_cents: money is stored as integer minor units (cents), never as a floating-point amount, because floats can't represent 0.10 exactly and you do not want rounding errors in money that has to reconcile against a payer's remittance. (We'll revisit money typing as a modeling standard in Chapter 16.)
Prove the constraints are real by trying to break them — this is the exercise that makes the model click:
INSERT INTO patients (mrn, full_name, date_of_birth) VALUES ('MRN-4471', 'Ada Lovelace', '1815-12-10'); -- ok, id = 1
INSERT INTO patients (mrn, full_name, date_of_birth) VALUES ('MRN-4471', 'A. Lovelace', '1815-12-10');
-- ERROR: duplicate key value violates unique constraint "patients_mrn_key"
INSERT INTO claims (patient_id, cpt_code, charge_amount_cents)
VALUES (999, '99213', 15000);
-- ERROR: insert or update on table "claims" violates foreign key constraint
-- (Key (patient_id)=(999) is not present in table "patients".)
INSERT INTO claims (patient_id, cpt_code, charge_amount_cents)
VALUES (1, '99213', -100);
-- ERROR: new row for relation "claims" violates check constraint "claims_charge_amount_cents_check"
Three writes, three engine refusals — and not one of those refusals depended on your application code being correct. That's the entire point.
Building SQL fluency
With the schema in place, build the query vocabulary you'll lean on forever. The order matters, because each piece builds on the last.
SELECT … FROM … WHERE filters rows by a predicate, remembering 3VL — WHERE keeps only TRUE rows:
SELECT id, cpt_code, charge_amount_cents FROM claims WHERE status = 'submitted' AND charge_amount_cents <= 50000;
Note: explicit columns, never SELECT * in application code — it ships extra bytes and breaks silently when someone adds a column.
JOIN … ON, in each flavor. The anti-join — "patients with zero claims" — has two correct spellings, and seeing them agree is a great way to internalize the join shapes:
-- Anti-join, idiom A: LEFT JOIN where the right side came back NULL (no match was found)
SELECT p.id, p.full_name
FROM patients p
LEFT JOIN claims c ON c.patient_id = p.id
WHERE c.id IS NULL; -- the NULL-pad from §3 means "this patient matched nothing"
-- Anti-join, idiom B: NOT EXISTS — preferred, and NULL-safe (see §6 for why NOT IN is not)
SELECT p.id, p.full_name
FROM patients p
WHERE NOT EXISTS (SELECT 1 FROM claims c WHERE c.patient_id = p.id);
GROUP BY + aggregates partition the set into groups and collapse each to one row. The rule that trips everyone: every column in SELECT that isn't inside an aggregate must appear in GROUP BY (because the engine has to know how to collapse it):
SELECT patient_id, COUNT(*) AS claim_count, MAX(charge_amount_cents) AS largest
FROM claims
WHERE status = 'submitted'
GROUP BY patient_id; -- patient_id is grouped; the rest are aggregated. Legal.
HAVING vs WHERE — the classic confusion, resolved by when each runs. WHERE filters rows before grouping; HAVING filters groups after grouping. You cannot reference an aggregate in WHERE (the groups don't exist yet), and you shouldn't put a row predicate in HAVING (it's slower and clearer in WHERE):
-- "Patients with more than 5 submitted claims": the COUNT is a per-group fact → HAVING.
SELECT patient_id, COUNT(*) AS submitted_count
FROM claims
WHERE status = 'submitted' -- per-ROW filter: only submitted claims enter the grouping
GROUP BY patient_id
HAVING COUNT(*) > 5; -- per-GROUP filter: only patients whose group is large enough
Try to put COUNT(*) > 5 in WHERE and Postgres errors with "aggregate functions are not allowed in WHERE" — not arbitrary fussiness, but a direct consequence of evaluation order (below).
Subqueries come in three shapes: scalar (returns one value, usable anywhere a value is), IN (membership against a set), and correlated EXISTS (references the outer row and conceptually re-evaluates per outer row):
-- Correlated EXISTS: for each outer patient, check whether any matching submitted claim exists.
SELECT p.full_name
FROM patients p
WHERE EXISTS (SELECT 1 FROM claims c WHERE c.patient_id = p.id AND c.status = 'submitted');
CTEs (WITH) name an intermediate relation so a multi-step query reads top-to-bottom instead of inside-out. This is the right tool for "top procedure codes by submitted-claim count," and it's far more readable than nesting:
WITH submitted AS ( -- step 1: name the relation "submitted claims"
SELECT cpt_code FROM claims WHERE status = 'submitted'
)
SELECT cpt_code, COUNT(*) AS n -- step 2: aggregate over the named relation
FROM submitted
GROUP BY cpt_code
ORDER BY n DESC
LIMIT 5;
A CTE is exactly §2's "queries compose" made syntactic — you named a relation-valued expression and fed it into the next step.
The logical evaluation order tutorials skip
Here is the thing most SQL tutorials never tell you, and the thing that explains why the rules above exist. SQL is written SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT, but it is logically evaluated in a different order:
FROM ──▶ WHERE ──▶ GROUP BY ──▶ HAVING ──▶ SELECT ──▶ ORDER BY ──▶ LIMIT
(build the (filter (partition (filter (compute (sort the (cut to
row set) rows) into groups) groups) output cols result) N rows)
+ aliases)
Read this pipeline once and three "arbitrary" rules become obvious:
- Why you can't use a
SELECTalias inWHERE:WHEREruns beforeSELECT, so the alias doesn't exist yet whenWHEREis evaluated. - Why you can't reference an aggregate in
WHERE:WHEREruns beforeGROUP BY, so there are no groups and no aggregates to reference — that'sHAVING's job, which runs after grouping. - Why
ORDER BYcan use aSELECTalias:ORDER BYruns afterSELECT, so the alias is in scope.
Memorize this pipeline and most SQL "errors" stop being mysteries and start being predictable.
Running it from Node — and where TypeScript stops protecting you
This is the backend-engineer's lab. From Node, you talk to Postgres via the pg driver, and there is exactly one correct way to pass values into a query — parameterized queries (placeholders where the values travel to the engine separately from the SQL text, never spliced into it):
import { Pool } from 'pg';
const pool = new Pool();
// CORRECT: $1, $2 are placeholders; values travel OUT-OF-BAND, never parsed as SQL.
async function findSubmittedByCpt(cptCode: string, maxCents: number) {
const { rows } = await pool.query(
`SELECT id, cpt_code, charge_amount_cents
FROM claims
WHERE cpt_code = $1 AND status = 'submitted' AND charge_amount_cents <= $2
ORDER BY charge_amount_cents ASC`,
[cptCode, maxCents], // ← values bound here, separately from the SQL text
);
return rows;
}
The $1/$2 placeholders are not string templating. The driver sends the SQL text and the values to Postgres separately; the engine parses the query structure first, then plugs values into already-parsed slots. A value can therefore never be reinterpreted as SQL syntax — which is the entire structural defense against SQL injection (§8). Contrast the catastrophe:
// NEVER. This is the SQL injection hole. `cptCode` is parsed as SQL.
const bad = await pool.query(
`SELECT * FROM claims WHERE cpt_code = '${cptCode}'` // ☠️ cptCode = "x'; DROP TABLE claims;--"
);
One more thing the backend dev must internalize: the rows come back as plain JS objects, and any TypeScript types you put on them are a claim, not a guarantee. You can write const rows = result.rows as Claim[], but pg did not verify that — it handed you whatever shape the database returned, and your as assertion is exactly the kind of unchecked claim you were warned about earlier, now at the database boundary. The database's CHECK and NOT NULL constraints are enforced; your TypeScript interface is aspirational. The runtime truth lives in the schema; the compile-time type is a convenience that the network boundary can quietly violate — the same TypeScript-versus-runtime seam you've already met. If you need a runtime guarantee on the way out, you validate (e.g. with a schema validator) — but the authoritative guarantee is, as always, in the database.
The Java contrast — to prove parameterization is language-agnostic
Bring in Java/Spring for exactly one reason: to show that "bind variables, don't concatenate" is not a pg-driver nicety but a property of the database protocol itself, identical across every ecosystem. (Skip the Java syntax if it's noise to you — the transferable payoff is the last sentence.)
// JDBC PreparedStatement — same out-of-band parameterization, different syntax.
PreparedStatement ps = conn.prepareStatement(
"SELECT id, cpt_code FROM claims WHERE cpt_code = ? AND charge_amount_cents <= ?");
ps.setString(1, cptCode); // bound, not concatenated
ps.setInt(2, maxCents);
ResultSet rs = ps.executeQuery();
The ? placeholders and setString/setInt are JDBC's spelling of $1/$2. The principle is the engine's, not the library's: the structure of the query is fixed before any value touches it. Whether you write Node, Java, Go, or Python, the rule is the same and non-negotiable.
🛑 What we deliberately did not explain. How Postgres actually executes these queries — whether
WHERE cpt_code = $1scans every page or navigates an index, howGROUP BYis computed (hash vs sort), where the rows physically live on disk, and how aJOINis realized (nested loop, hash join, merge join). We named "the engine picks a strategy"; we did not open the engine. Storage internals — pages, the write-ahead log, B-trees — are Chapter 18, and PostgreSQL's specific machinery (its planner, MVCC, index types,EXPLAIN) is Chapter 19. The transactional guarantees that make "check-then-insert" safe to reason about — atomicity, isolation, and what concurrent writers actually see — are Chapter 17. That chapter is where Pulsely's three distinct concurrency problems get their real tools: no-double-booking an appointment slot, submitting a claim exactly once, and two clinicians charting the same encounter at once without silently overwriting each other. This chapter owns the model and the language; those own the machine.
5. In production: schema decisions that age well
The schema in §4 works. Making it a schema that survives three years of a growing product is a set of deliberate choices, each of which a senior engineer makes on purpose. Here's the production checklist.
Pick surrogate vs natural keys deliberately — and usually pick surrogate. A natural key is a real-world identifier (MRN, NPI, an ICD-10 code). A surrogate key is a meaningless, stable, engine-generated id (BIGINT IDENTITY or UUID). Pulsely's patients.id is surrogate; mrn is a natural candidate key kept as a UNIQUE constraint. Why? Because real-world identifiers change — a patient's MRN gets corrected or merged when two charts are reconciled, an NPI is reassigned — and if you'd made mrn the primary key, that change would cascade through every foreign key in the database that referenced it (every claim, every encounter, every observation). The surrogate id never changes, so foreign keys point at something stable, while the UNIQUE(mrn) constraint still gives you the business guarantee. Surrogate PK for stability; natural key as UNIQUE for the business rule. You get both. The exception: small, genuinely-immutable reference data — the code systems Pulsely leans on (icd10_codes, cpt_codes, loinc, rxnorm) — are fine keyed on the code itself, because the code is the stable identity and it never changes.
Always declare foreign keys in OLTP unless you have a measured reason not to. An FK is the cheapest guarantee you will ever buy against orphaned rows, and "we removed FKs for performance" is, nine times in ten, cargo-culting. Declare the FK, and choose the referential action per relationship: ON DELETE RESTRICT as the default (refuse to delete a parent with children — make orphaning an explicit act), CASCADE only where the child genuinely cannot outlive the parent (a claim's diagnosis lines cannot exist without their claim), and SET NULL only for truly optional links on a nullable column.
NOT NULL by default; nullability is a decision you justify. Every column starts NOT NULL. When you make one nullable, write down — in a comment or the modeling doc — what NULL means for that column, because NULL is overloaded: it can mean "absent," "not yet known," or "not applicable," and those are three different facts. A date_of_death that's NULL means "the patient is alive"; a discharge_at that's NULL means "still admitted"; a middle_name that's NULL means "none / not provided." Conflating them is how 3VL bugs breed.
Use CHECK to encode enums and ranges, not the app. CHECK (status IN (...)) and CHECK (charge_amount_cents >= 0) belong in the engine precisely because the app is one of several writers. The day a data-migration script or a teammate's new service writes status = 'pending' (a value you never intended), the CHECK catches it at the source instead of letting it rot until a switch statement in the claims pipeline falls through.
Naming conventions, chosen once and held. Pick singular or plural table names and never mix (this book uses plural: patients, claims). Use snake_case for everything (Postgres folds unquoted identifiers to lowercase anyway). Name foreign keys predictably (patient_id, not patient), and name your constraints explicitly (CONSTRAINT claims_charge_amount_cents_check ...) so error messages and migrations are diagnosable instead of referencing an auto-generated name nobody can map back to intent.
Schema is reviewed code, not GUI clicks. Your CREATE TABLE statements live in version control as the source of truth. Everyone who checks out the repo gets the same enforced shape; changes go through review like any other code. The full tooling for evolving a live schema safely — migrations, expand/contract, zero-downtime ALTER — is later in the book (Chapter 38 and Chapter 16's modeling practice); the discipline you adopt now is simply: the schema is code, reviewed and versioned, never a thing someone clicks in a database GUI on a Friday.
Select explicit columns; never SELECT * in app code. It breaks silently when someone adds or reorders columns, ships bytes you don't use, and couples your code to the table's full shape. Name the columns you need — and in a system holding PHI, naming columns is also how you stop accidentally hauling protected fields into a log or a response that never needed them.
🏭 The deepest production reason to push correctness into constraints is plurality of writers. In dev, you are the only one touching the database, so app-level checks feel sufficient. In production, the database is hit by your API, your background RPM-ingest workers, your nightly claims batch, your migrations, an analyst's ad-hoc
psqlsession, a clearinghouse or lab partner integration, and the emergency manualUPDATEsomeone runs at 3 a.m. during an incident. The constraint is the only rule that holds across all of them. Every invariant you can express in the schema is an invariant you no longer have to trust six different code paths to remember — and in healthcare, one forgetful code path is how a claim ends up attached to the wrong patient.