intermediate · 22 minute study
Make impossible relationships unrepresentable
A form can look correct while an import or competing request writes a broken relationship. Integrity belongs at the data boundary every writer shares.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Subqueries — An existing guided foundation in Learn → Try → Test → Build.
First, build a mental model
A schema is a collection of promises about every possible saved row. A foreign key connects identities; a composite foreign key can connect identity AND company.
- A primary key identifies a row. A foreign key requires a referenced key to exist; it does not infer that two independent company columns agree.
- NOT NULL rejects missing values. CHECK rejects false, while a NULL result does not violate a PostgreSQL CHECK; pair the two when missing values are invalid.
- The ordered columns of a composite foreign key must match a unique or primary key in the parent. This encodes the relationship rather than trusting a browser filter.
- The example runs in the SQLite lab with foreign keys enabled. PostgreSQL also supports these constraints; schema evolution and locking differ between engines.
CREATE TEMP TABLE depots (
company_id TEXT NOT NULL, id INTEGER NOT NULL,
PRIMARY KEY (company_id, id)
);
CREATE TEMP TABLE bins (
company_id TEXT NOT NULL, depot_id INTEGER NOT NULL,
units INTEGER NOT NULL CHECK (units >= 0),
FOREIGN KEY (company_id, depot_id)
REFERENCES depots(company_id, id)
);
INSERT INTO depots VALUES ('company-a', 7);
INSERT INTO bins VALUES ('company-a', 7, 3);- Parent
The parent identity is the pair (company-a, 7), not merely the number 7.
- Child
The valid bin points at that exact pair and contains a non-null, nonnegative count.
- Counterexample
Changing only the bin company to company-b produces a missing parent pair, even though depot 7 exists elsewhere.
Production thinking
Take this beyond the example.
Design invalid examples before designing a schema: missing parent, wrong-company parent, null count and duplicate identity. A green form test does not prove any of these database invariants.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Keep missing relationships visible →