Keys, constraints and normalisation
Every lesson so far has taken the schema as given. This one is about choosing it, which is where most of the problems the earlier lessons describe are either created or prevented.
Constraints are the cheapest correctness you will ever buy
A constraint is a rule the database enforces for every writer, forever, including the migration script someone runs by hand at 2am and the service nobody remembered was still writing.
CREATE TABLE project (
id int PRIMARY KEY,
name text NOT NULL,
owner_id int NOT NULL REFERENCES employee(id),
budget numeric(12,2) NOT NULL CHECK (budget >= 0),
started_on date NOT NULL,
ended_on date,
CHECK (ended_on IS NULL OR ended_on >= started_on),
UNIQUE (name)
);
Five kinds of rule in one declaration:
PRIMARY KEY— unique and not null, and the row’s identityNOT NULL— the single highest-value constraint, because it removes a whole class of three-valued-logic bugs from every query that touches the column. See NULLs in joins and filters for what you are buying your way out ofREFERENCES— a foreign key; the referenced row must existCHECK— any boolean condition, including across columns of the same rowUNIQUE— no duplicates, and it creates an index, so it is also a performance decision
Application-level validation does not replace any of these. It runs in one service, in one version, for writers that go through it.
INSERT INTO project VALUES (1, 'Atlas', 999, 100, '2024-01-01', NULL);
The foreign key rejects employee 999, which does not exist. That is a bug caught at the boundary rather than discovered by a report six months later.
Natural versus surrogate keys
A natural key is data that identifies the row — an email, an ISBN, a country code. A surrogate key is a meaningless identifier you generate.
Prefer a surrogate, for one reason above all: natural keys change. People change email addresses, companies rename products, countries change codes. A natural key as a primary key means that change cascades through every table referencing it.
Natural keys are still worth declaring — as UNIQUE. That gets the correctness
guarantee without making it the thing other tables point at.
On the choice of surrogate: a sequential bigint is dense, index-friendly and
sorts in insert order. A uuid can be generated client-side without a round
trip and does not leak volume, but random uuids scatter index writes across
pages — the contention point from the
locking lesson. If uuids are needed, a
time-ordered variant keeps the locality.
Normalisation, by the anomaly each form removes
Normal forms are usually taught as definitions. They are easier to remember as answers to “what goes wrong if you don’t”.
First normal form — no repeating groups. One value per column.
A tags column holding 'urgent,billing,escalated' cannot be indexed usefully,
cannot be joined, and needs string surgery to query. The fix is a row per tag.
Postgres arrays and jsonb are a legitimate middle ground when the content is
genuinely opaque to queries — the moment you are searching inside it, it wanted
to be rows.
Second normal form — no partial dependency on a composite key. If the key is
(order_id, product_id) and a column depends only on order_id, it belongs on
the order.
Third normal form — no transitive dependency. If employee holds
department_id and department_name, the name depends on the department, not
the employee. Which means:
- the same department’s name is stored many times (storage)
- a rename has to update every employee row (update anomaly)
- two rows can disagree about the same department’s name (inconsistency)
- a department with no employees cannot exist at all (insertion anomaly)
Those four are what third normal form buys, and “3NF” is just the shorthand. Most well-designed transactional schemas are in 3NF, and that is the sensible default.
When to denormalise, and how to keep it honest
Denormalisation is a deliberate trade: duplicate data to avoid a join or an aggregate, and accept that the copy can drift.
It is justified when a read is hot, the join is expensive, and the data is nearly immutable. Two examples that are almost always right:
- A captured value that must not change. An order line stores the price at the time of sale. That is not a denormalised copy of the product price, it is a different fact, and normalising it away would be a bug.
- A maintained aggregate. A
comment_counton a post, when the count is read on every page view and the posts table is read-heavy.
The thing that makes the second one safe is who maintains it. A counter updated by whichever service remembers will drift. A counter maintained by a trigger, or recomputed on a schedule, or owned by exactly one code path, will not. If you cannot name the single mechanism that keeps a denormalised value true, it will eventually be false.
Indexes are part of schema design
From how an index works: every index is write amplification. So the schema decisions that matter are:
- a
UNIQUEconstraint gives you an index whether you wanted one or not - a foreign key does not create an index on the referencing column in Postgres, and you almost always want one — otherwise every delete of a parent row scans the child table
- composite index column order follows the queries, not the schema’s sense of importance
Try it
The CREATE TABLE project statement and its failing insert both run in the
SQL playground. Watching the foreign key reject employee
999 is the argument for declaring it.
Drill it with
Find orphaned rows and
Find the double booked rooms, which
ends at the EXCLUDE constraint that would have prevented it.
Schema design at the system level — sharding keys, read replicas, which service owns which table — is the HLD fundamentals, and SQL vs NoSQL is the next lesson’s subject.
Interview questions
1. Why prefer a surrogate key over a natural one?
Because natural keys change — emails, codes, names — and a change cascades
through every referencing table. Declare the natural key UNIQUE to keep the
guarantee without making it the reference target.
2. What does third normal form actually prevent? Four things, from storing a fact that depends on another non-key column: duplication, update anomalies when the fact changes, inconsistency between copies, and the inability to record the fact without a dependent row.
3. Why is NOT NULL the highest-value constraint?
It removes three-valued logic from every query touching the column — NOT IN,
<> and count(column) all stop having special cases — and it lets the planner
reason more precisely.
4. Does a foreign key create an index in Postgres? It creates one on the referenced side as part of the primary key or unique constraint, but not on the referencing column. Without one, deleting a parent row scans the child table for references.
5. When is denormalisation the right call? When a read is hot, the join or aggregate is expensive, and the duplicated data is nearly immutable — or when the stored value is a captured fact, like a price at time of sale, which is a different fact rather than a copy. And only with one named mechanism maintaining it.
6. Is a comma-separated tags column ever acceptable?
Only if nothing ever queries inside it. The moment you filter or join on
individual tags it needs to be rows, or at minimum a real array or jsonb
column with an index — string surgery in a WHERE clause is neither indexable
nor correct at the edges.
Next
When not to use SQL — the last lesson, and the one that puts the whole track in context.