DB·55
The Relational Model
The ideas underneath every SQL database: relations, tuples and attributes, tables, rows and columns, domains and data types, keys (candidate, primary, natural, surrogate, composite), relationships and foreign keys with referential actions, unique and check constraints, NULL and three-valued logic, and normalisation from 1NF to BCNF and when to denormalise. PostgreSQL is the reference engine, compared with MySQL, SQLite, SQL Server and Oracle.
Start here: one fact in one place
The spreadsheet trap
Most data starts life as a spreadsheet: one big table, one row per thing that happened. For the café, one row per dish ordered:
CREATE TABLE flat_orders (order_no int, customer text, phone text, dish text, price_paise int, qty int);
INSERT INTO flat_orders VALUES
(1, 'Asha', '98450-11111', 'Masala dosa', 9000, 2),
(1, 'Asha', '98450-11111', 'Filter coffee', 3000, 2),
(2, 'Ravi', '99000-22222', 'Thali', 18000, 1),
(3, 'Asha', '98450-11111', 'Idli', 5000, 2);
It looks fine until the data changes. Asha gets a new number, and someone updates "her latest order":
UPDATE flat_orders SET phone = '98450-99999' WHERE order_no = 3;
SELECT DISTINCT customer, phone FROM flat_orders WHERE customer = 'Asha';
customer | phone
----------+-------------
Asha | 98450-11111
Asha | 98450-99999
Which is her number now? The database can't say, because the same fact (Asha's phone) is stored in three places and only one was changed. Then Ravi cancels his only order:
DELETE FROM flat_orders WHERE order_no = 2;
SELECT count(*) AS rows_mentioning_thali FROM flat_orders WHERE dish = 'Thali';
rows_mentioning_thali
-----------------------
0
Deleting an order also deleted the only record that the café sells a Thali at ₹180. And there's no way to add a new dish to the menu until someone orders it. These are the three classic anomalies of redundant data: update (copies disagree), delete (removing one fact loses another) and insert (one fact can't be recorded without another).
Normalising: split by what the facts are about
The cure is to give each kind of thing its own table, so each fact is stored once, and connect them with keys:
CREATE TABLE customer (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, phone text NOT NULL UNIQUE);
CREATE TABLE dish (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL UNIQUE, price_paise int NOT NULL CHECK (price_paise > 0));
CREATE TABLE orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customer,
placed_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE order_line (order_id bigint NOT NULL REFERENCES orders ON DELETE CASCADE, dish_id bigint NOT NULL REFERENCES dish,
qty int NOT NULL CHECK (qty > 0), unit_price_paise int NOT NULL, PRIMARY KEY (order_id, dish_id));
Now the same changes are each a single, unambiguous statement:
UPDATE customer SET phone = '98450-99999' WHERE name = 'Asha'; -- one row
DELETE FROM orders WHERE id = 2; -- its lines go too (ON DELETE CASCADE)
order_no | name | phone | dish | qty | unit_price_paise
----------+------+-------------+---------------+-----+------------------
1 | Asha | 98450-99999 | Filter coffee | 2 | 3000
1 | Asha | 98450-99999 | Masala dosa | 2 | 9000
3 | Asha | 98450-99999 | Idli | 2 | 5000
SELECT name FROM dish ORDER BY id; → Masala dosa, Filter coffee, Thali, Idli
Asha has one phone number everywhere, and the Thali survived Ravi's cancellation because dishes no longer depend on orders. The query that rebuilds the "spreadsheet view" is a join (chapter 56). Note one deliberate copy: order_line.unit_price_paise records the price at the time of the order, which is a different fact from the dish's current price. Normalisation is about not duplicating the same fact, not about never repeating a value.
Relationships and keys
The tables encode three kinds of relationship:
- One-to-many: a customer has many orders; each order has one customer. The "many" side holds a foreign key (
orders.customer_id). - Many-to-many: an order contains many dishes and a dish appears in many orders. It needs a junction table (
order_line), whose primary key here is the pair(order_id, dish_id). - One-to-one: rarer; a table split in two, sharing a key.
A primary key must be unique and never change. Surrogate keys (generated numbers or UUIDs, like id here) are the norm because real-world identifiers (names, phone numbers) change; keep the real-world uniqueness as a UNIQUE constraint, as customer.phone does.
NULL means "unknown"
NULL isn't zero or an empty string: it means "no value known", and SQL reasons about it with three-valued logic (true, false, unknown):
INSERT INTO note VALUES ('Masala dosa', NULL), ('Idli', 'none'), ('Vada', 'gluten');
SELECT count(*) AS total, count(allergen) AS known FROM note; → total 3, known 2
SELECT dish FROM note WHERE allergen <> 'gluten'; → Idli
SELECT NULL = NULL, NULL IS NULL, (NULL OR true), (NULL AND false); → (null), t, t, f
Masala dosa isn't returned by allergen <> 'gluten': its allergen is unknown, so "is it not gluten?" is unknown, and WHERE keeps only rows where the condition is true. NULL = NULL is unknown too, which is why you test with IS NULL. count(column) skips NULLs. Decide deliberately which columns may be NULL (mostly: as few as possible), because every nullable column adds these cases to every query.
How deep to go in the relational model
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain tables, keys, relationships, constraints and NULL |
| L2 | Design a normalised schema with appropriate types, keys and constraints |
| L3 | Explain relational theory, functional dependencies, the normal forms, three-valued logic and key strategies |
| L4 | Diagnose anomalies, NULL bugs, type mistakes (floats for money, naive timestamps) and missing foreign-key indexes |
| L5 | Choose where to denormalise, how to model history, and key and type strategies for scale |
| L6 | Govern schemas and their evolution across many teams and services |
Why the relational model
Data independence
Before 1970, databases were navigational. In hierarchical (IBM IMS) and network (CODASYL) databases, programs followed pointers from record to record. Queries were procedures that walked a physical structure, so changing the storage layout broke the programs.
Edgar F. Codd's 1970 paper "A Relational Model of Data for Large Shared Data Banks" proposed something radical. Represent all data as relations (mathematical sets of tuples). Query it declaratively: say what you want, not how to find it. Let the system decide the access path. This is data independence:
- Logical: applications see tables, not storage.
- Physical: you can add an index, reorganise storage or partition a table without changing a single query.
Fifty years later, the model's descendants (PostgreSQL, MySQL, SQLite, SQL Server, Oracle, and the distributed SQL systems: CockroachDB, YugabyteDB, Spanner, TiDB) are still the default choice for most applications. Chapter 62 covers when they aren't.
Relations, tuples and attributes
| Relational theory | SQL | Everyday term |
|---|---|---|
| Relation | Table | Table |
| Tuple | Row | Record |
| Attribute | Column | Field |
| Domain | Data type (+ constraints) | Type |
| Relation schema | Table definition | Schema |
| Degree / cardinality | Number of columns / rows | — |
In the pure model, a relation is a set: tuples have no order, and there are no duplicates. Attributes have no order, and each value is atomic, drawn from its domain. SQL deviates in practical ways:
- SQL tables are bags (multisets): duplicate rows are allowed unless a key forbids them, and
SELECT DISTINCTremoves them. - Columns have a declared order (
SELECT *depends on it). - NULL exists. Codd later added it; C. J. Date and others argue it breaks the model's logic (below).
Relational algebra, the mathematical basis of query execution, has a handful of operators. SQL is a (verbose) syntax for them, and query plans (chapter 60) are trees of them:
| Operator | Meaning | SQL |
|---|---|---|
| Selection σ | Filter rows | WHERE |
| Projection π | Choose columns | SELECT col, … |
| Join ⋈ | Combine related tuples | JOIN … ON |
| Union ∪, difference −, intersection ∩ | Set operations | UNION, EXCEPT, INTERSECT |
| Rename ρ | Rename attributes | AS |
| Aggregation γ (an extension) | Group and summarise | GROUP BY |
Because these operators have algebraic laws (selections commute, joins are associative), the optimiser can rewrite a query into an equivalent, cheaper one. You get that power because you described the result, not the procedure.
Tables, rows and columns
Defining tables
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- surrogate key (SQL-standard identity)
email text NOT NULL,
display_name text NOT NULL CHECK (length(display_name) BETWEEN 1 AND 100),
country_code char(2) NOT NULL CHECK (country_code ~ '^[A-Z]{2}$'),
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT customers_email_key UNIQUE (email) -- named constraints → readable errors
);
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT uuidv7(), -- PostgreSQL 18: time-ordered UUIDs
customer_id bigint NOT NULL REFERENCES customers (id), -- foreign key
status text NOT NULL DEFAULT 'PENDING'
CHECK (status IN ('PENDING','PAID','SHIPPED','CANCELLED')),
total_cents bigint NOT NULL CHECK (total_cents >= 0), -- money as integer minor units
currency char(3) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
paid_at timestamptz, -- nullable: not paid yet
CHECK (status <> 'PAID' OR paid_at IS NOT NULL) -- cross-column rule
);
CREATE TABLE order_lines (
order_id uuid NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
line_no int NOT NULL,
sku text NOT NULL,
qty int NOT NULL CHECK (qty > 0),
unit_cents bigint NOT NULL CHECK (unit_cents >= 0),
PRIMARY KEY (order_id, line_no) -- composite key
);
Choosing data types
Choosing the right domain for each column is the first line of data quality. It's also a performance decision, because narrower types mean smaller rows, more rows per page and smaller indexes (chapter 58).
| Data | Good choice (PostgreSQL) | Avoid | Notes |
|---|---|---|---|
| Integer IDs, counts | bigint (8 B), int (4 B) |
int for IDs of big tables (2.1 billion overflows: real outages have happened) |
smallint for tiny enumerations |
| Money | bigint minor units, or numeric(19,4) |
float/double precision, money type |
Exact arithmetic (Vol. 3 ch. 33) |
| Decimal measurements | numeric(p,s) when exactness matters |
— | numeric is exact but slower than floats |
| Scientific values | double precision |
— | IEEE 754 |
| Text | text (or varchar(n) when a limit is a real business rule) |
char(n) for variable data (blank-padded) |
PostgreSQL stores text and varchar identically; use a CHECK for length rules |
| Timestamps | timestamptz (stores an instant in UTC, displays in the session time zone) |
timestamp (without time zone) for instants |
Store instants as instants; store "wall clock" values (a store's opening hours) as time + a zone name |
| Dates | date |
Strings | — |
| Durations | interval |
Integers of unknown unit | — |
| Booleans | boolean |
'Y'/'N' strings |
— |
| UUIDs | uuid (16 B) |
text (36+ B) |
uuidv7() (PG 18) for index-friendly ordering |
| Enumerations | text + CHECK, a lookup table, or CREATE TYPE … AS ENUM |
— | Enums are compact but awkward to change (you can add values, but not remove or reorder them easily) |
| Semi-structured | jsonb |
json (text, re-parsed), or text |
Chapter 56 |
| IP addresses, ranges, arrays, geometry | inet/cidr, tstzrange/int4range, int[], PostGIS geometry |
Strings | PostgreSQL's rich types are a strength |
Engine differences worth knowing:
- MySQL:
DATETIME(no time zone) versusTIMESTAMP(stored in UTC, with a 2038 limit in older versions).utf8is a 3-byte subset, so useutf8mb4, which is the default since 8.0.TINYINT(1)serves as a boolean. - SQLite: type affinity. Columns accept any type unless the table is declared
STRICT(3.37+). There's no native date type (dates are stored as text, real or integer). - SQL Server:
datetime2,datetimeoffset,nvarcharfor Unicode,uniqueidentifier(sorted by GUID byte order, not left to right). - Oracle:
NUMBER,VARCHAR2, and the infamous rule that the empty string is NULL.
Keys and constraints
Keys
A key is a set of columns whose values uniquely identify a row:
- Superkey: any set of columns that's unique (including "all columns").
- Candidate key: a minimal superkey (remove any column and it's no longer unique). A table can have several:
customershasidandemail. - Primary key: the candidate key chosen as the main identifier. It's
NOT NULLandUNIQUE, and there's one per table. In PostgreSQL it gets a unique B-tree index. In InnoDB (MySQL) and SQL Server it's usually the clustered index, so the table's rows are physically stored in primary key order (chapter 58). - Alternate keys: the other candidate keys, enforced with
UNIQUEconstraints. - Composite key: a key of several columns (
(order_id, line_no)). - Foreign key: a column (or set) referencing a candidate key in another table (or the same one).
Natural or surrogate keys?
| Natural key (business data: email, ISBN, country code, SKU) | Surrogate key (meaningless: identity, sequence, UUID) | |
|---|---|---|
| Meaning | Real-world identifier | None |
| Stability | Can change (people change emails; codes get reassigned), and changes cascade to every referencing table | Never changes |
| Size | Often wide (strings), making FKs and indexes larger | Compact (bigint, uuid) |
| Uniqueness guarantee | Depends on the outside world (are ISBNs really unique? Not always) | Guaranteed by the generator |
| Joins | Sometimes avoid a join (the code is the data) | Always need a join to get meaning |
The common practice is a surrogate primary key plus a UNIQUE constraint on the natural key(s): stable references, and business uniqueness still enforced. Natural keys work well for small, truly stable code tables (ISO country and currency codes).
Surrogate key generation:
| Method | Pros | Cons |
|---|---|---|
bigint identity / sequence |
Compact, ordered, fast inserts (append to the end of the index) | Guessable and enumerable (don't expose them raw if that matters); needs the database to assign; harder to merge across databases or shards |
| UUIDv4 (random) | Generate anywhere (client, app, offline); unguessable; merge-friendly | 16 bytes; random inserts scatter across the B-tree: page splits, poor cache locality, write amplification (chapter 58) |
| UUIDv7 (RFC 9562, 2024: timestamp + random) | Generate anywhere and roughly time-ordered, so it inserts near the end of the index like a sequence | Leaks creation time; 16 bytes |
| ULID, Snowflake IDs (64-bit: timestamp + worker + sequence) | Ordered, compact (Snowflake fits in bigint) |
Need a scheme or coordination for worker IDs |
PostgreSQL 18 added a native uuidv7() function (uuidv4() is an alias of gen_random_uuid()). Libraries generate UUIDv7 in every language: Java uuid-creator/java-uuid-generator, Go github.com/google/uuid (uuid.NewV7()), Rust uuid with the v7 feature, Python 3.14's uuid.uuid7(), and .NET 9's Guid.CreateVersion7().
Relationships
Relationships are expressed with foreign keys:
- One-to-many (the most common): the foreign key lives on the "many" side (
orders.customer_id). - Many-to-many: a junction (association) table with two foreign keys and a composite primary key. It often grows its own attributes (
added_at,position,role), at which point it's an entity in its own right (enrolments,memberships). - One-to-one: the dependent table's primary key is also a foreign key (a shared primary key), or a foreign key plus
UNIQUE. It's used to split rarely accessed or large columns, or optional extensions. - Self-referencing:
employees.manager_id REFERENCES employees(id), a tree or graph queried with recursive CTEs (chapter 56). - Polymorphic associations ("
comments.target_type+target_idpointing at different tables") can't be enforced with a foreign key. Prefer separate nullable FK columns with aCHECKthat exactly one is set, or separate junction tables.
Foreign keys and referential actions
A foreign key constraint guarantees referential integrity: every non-null FK value matches an existing key in the referenced table. The database enforces it on insert and update of the child, and on delete and update of the parent:
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id)
REFERENCES customers (id)
ON DELETE RESTRICT -- what happens to orders when a customer is deleted
ON UPDATE CASCADE; -- what happens when the referenced key changes (rare with surrogate keys)
| Action | On parent delete or update |
|---|---|
NO ACTION (default) |
Error if children exist (checked at the end of the statement, or at commit if deferred) |
RESTRICT |
Error immediately (not deferrable) |
CASCADE |
Delete or update the children too |
SET NULL / SET DEFAULT |
Set the child's FK column(s) to NULL or the default. PostgreSQL 15+ can set only some columns of a composite FK |
Practical guidance:
- Index foreign key columns. PostgreSQL does not create an index on the referencing column automatically (MySQL InnoDB does). Without one, deleting a parent requires a sequential scan of the child table to check for references, and joins from parent to children are slow. This is one of the most common PostgreSQL performance mistakes.
- Use
CASCADEfor compositions (deleting an order deletes its lines, Vol. 3 ch. 34), andRESTRICT/NO ACTIONfor associations (don't silently delete a customer's orders). - Deferrable constraints (
DEFERRABLE INITIALLY DEFERRED) are checked at commit. That's useful for circular references or bulk loads that temporarily violate order. - Adding FKs to big live tables:
ADD CONSTRAINT … NOT VALID(instant: enforced for new rows only), thenVALIDATE CONSTRAINT(scans without blocking writes). - Should microservices use FKs across services? They can't: each service owns its database (Vol. 5), and integrity across services is eventual. Within a service's database, FKs are cheap insurance against bugs.
- Engines: MySQL enforces FKs only in InnoDB. SQLite has FK enforcement off by default: run
PRAGMA foreign_keys = ON;per connection.
Unique constraints
UNIQUE guarantees that no two rows share the same value (or combination of values), backed by a unique index:
ALTER TABLE customers ADD CONSTRAINT customers_email_key UNIQUE (email);
-- Case-insensitive uniqueness: a unique index on an expression
CREATE UNIQUE INDEX customers_email_lower_key ON customers (lower(email));
-- (or the citext extension, or a nondeterministic ICU collation)
-- Partial uniqueness: only one ACTIVE subscription per customer
CREATE UNIQUE INDEX one_active_sub ON subscriptions (customer_id) WHERE status = 'ACTIVE';
-- NULL handling: by default NULLs are distinct (many NULLs allowed). PostgreSQL 15+:
ALTER TABLE devices ADD CONSTRAINT devices_serial_key UNIQUE NULLS NOT DISTINCT (serial); -- at most one NULL
Uniqueness is the right tool for idempotency (Vol. 3 ch. 45/51): INSERT … ON CONFLICT (idempotency_key) DO NOTHING relies on a unique constraint, and it's the only race-free way to guarantee "one per X". An application-level "check, then insert" has a race window between the check and the insert. The database constraint closes it.
Engine differences: SQL Server treats NULLs as equal in unique constraints (only one NULL allowed; use a filtered index WHERE col IS NOT NULL for "many NULLs"). Oracle doesn't index entirely-NULL keys, so many NULLs are allowed. MySQL allows many NULLs.
Exclusion constraints (PostgreSQL) generalise uniqueness to "no two rows overlap": the classic example is no double-booked rooms. PostgreSQL 18 adds temporal PRIMARY KEY/UNIQUE … WITHOUT OVERLAPS and FOREIGN KEY … PERIOD (chapter 57).
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
room_id int NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&) -- same room AND overlapping time → rejected
);
Check constraints
CHECK enforces a boolean condition on each row:
ALTER TABLE products
ADD CONSTRAINT price_positive CHECK (price_cents > 0),
ADD CONSTRAINT sale_below_price CHECK (sale_price_cents IS NULL OR sale_price_cents < price_cents),
ADD CONSTRAINT sku_format CHECK (sku ~ '^[A-Z0-9-]{3,32}$');
- A CHECK passes when the expression is TRUE or NULL.
CHECK (qty > 0)allowsqty IS NULLunless the column is alsoNOT NULL. - CHECK constraints see only the current row. Rules involving other rows or tables need unique or exclusion constraints, foreign keys, triggers, or application logic in a serialisable transaction (chapter 59).
- MySQL ignored CHECK constraints entirely before 8.0.16 (it parsed them and silently did nothing), which is a reminder to verify that your engine actually enforces what you declare.
- Domains package a type with constraints for reuse:
CREATE DOMAIN email AS text CHECK (VALUE ~ '^[^@\s]+@[^@\s]+$');.
Why put rules in the database at all, if the application validates? Because the database is the last line of defence. Every writer (other services, migrations, admin scripts, the next version of your app, bulk imports) goes through it. Application validation gives good error messages; constraints guarantee invariants. Use both, and map constraint violations (SQLSTATE 23505 unique, 23503 FK, 23514 check, 23502 not-null) to meaningful API errors (Vol. 3 ch. 48).
NULL and three-valued logic
What NULL means
NULL means "unknown" or "not applicable". It's a marker for absence, not a value. SQL therefore uses three-valued logic (3VL): every comparison is TRUE, FALSE or UNKNOWN.
| Expression | Result |
|---|---|
NULL = NULL |
UNKNOWN (not TRUE!) |
NULL <> 1 |
UNKNOWN |
NULL + 1 |
NULL |
TRUE AND UNKNOWN |
UNKNOWN |
FALSE AND UNKNOWN |
FALSE |
TRUE OR UNKNOWN |
TRUE |
NOT UNKNOWN |
UNKNOWN |
WHERE keeps rows only where the condition is TRUE, so UNKNOWN rows silently disappear:
SELECT * FROM orders WHERE paid_at = NULL; -- always returns NOTHING (UNKNOWN for every row)
SELECT * FROM orders WHERE paid_at IS NULL; -- correct
SELECT * FROM orders WHERE status <> 'CANCELLED'; -- rows with status NULL are EXCLUDED too (UNKNOWN)
-- The NOT IN trap: if the subquery returns any NULL, NOT IN returns no rows at all
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM blacklist); -- breaks if blacklist has a NULL
SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM blacklist b WHERE b.customer_id = c.id); -- safe
-- NULL-safe comparison
SELECT * FROM t WHERE a IS NOT DISTINCT FROM b; -- TRUE when both are NULL (MySQL: a <=> b)
More NULL behaviours:
- Aggregates ignore NULLs:
COUNT(col)counts non-null values, whileCOUNT(*)counts rows.AVGdivides by the non-null count.SUMof no rows (or only NULLs) is NULL, not 0, so useCOALESCE(SUM(x), 0). - Sorting: PostgreSQL sorts NULLs last in ascending order (first in descending). MySQL and SQL Server sort them first ascending. Use
NULLS FIRST/NULLS LASTexplicitly in PostgreSQL and Oracle. GROUP BYandDISTINCTtreat NULLs as equal (one group), which is inconsistent with=, but practical.- Oracle treats
''as NULL, soWHERE name = ''never matches. Portable code avoids relying on empty strings.
Nullability as a design decision
Default to NOT NULL. Make a column nullable only when absence is a real, meaningful state, and know what NULL means for that column ("not yet paid", "no manager", "unknown birthday"). Problems with careless NULLs:
- Bugs from 3VL (above).
- Ambiguity: does NULL in
discountmean "no discount" or "unknown"? Prefer0withNOT NULLwhen "none" is meant. - Application mapping: every nullable column becomes
Optional/null(Java), a pointer orsql.NullString(Go), orOption<T>(Rust) in code. - A table with many nullable columns that are "only set for type X" often signals a missing table (an optional 1:1, or a subtype table).
-- Adding a NOT NULL column to a large existing table without a long lock (PostgreSQL 11+):
ALTER TABLE orders ADD COLUMN channel text NOT NULL DEFAULT 'web'; -- constant default: metadata-only, instant
How languages see NULL:
// JDBC: primitives can't be null, so check wasNull() or use wrapper/getObject
long cents = rs.getLong("discount_cents"); // returns 0 for NULL!
boolean wasNull = rs.wasNull();
Long maybe = rs.getObject("discount_cents", Long.class); // null for NULL
Instant paidAt = rs.getObject("paid_at", OffsetDateTime.class) == null ? null : …;
// Go: database/sql needs Null* wrappers or pointers
var paidAt sql.NullTime
var discount *int64
err := row.Scan(&paidAt, &discount)
if paidAt.Valid { use(paidAt.Time) }
// Scanning NULL into a plain int64 returns an error: "converting NULL to int64 is unsupported"
// Rust (sqlx): nullability is in the type; query! checks it against the schema at compile time
let row = sqlx::query!("SELECT paid_at, discount_cents FROM orders WHERE id = $1", id)
.fetch_one(&pool).await?;
let paid_at: Option<OffsetDateTime> = row.paid_at; // nullable column → Option
# Python (psycopg): NULL ↔ None
cur.execute("SELECT paid_at FROM orders WHERE id = %s", (order_id,))
(paid_at,) = cur.fetchone() # None if NULL
Normalisation
Why normalise
Normalisation organises tables to eliminate redundancy and the update anomalies it causes. Consider an unnormalised orders table:
| order_id | customer_email | customer_name | sku | product_name | qty |
|---|---|---|---|---|---|
| 1 | ada@x.io | Ada | A1 | Chair | 2 |
| 1 | ada@x.io | Ada | B7 | Desk | 1 |
| 2 | ada@x.io | Ada | A1 | Chair | 4 |
- Update anomaly: Ada changes her name, and every one of her rows must change. Miss one and the data contradicts itself.
- Insert anomaly: you can't record a new product until someone orders it.
- Delete anomaly: delete order 2 and you might lose the only record of some product.
Normalisation decomposes the table using functional dependencies (FDs). X → Y means "the value of X determines the value of Y" (customer_email → customer_name, sku → product_name).
The normal forms
| Normal form | Rule | Violation example | Fix |
|---|---|---|---|
| 1NF | Atomic values; no repeating groups; a key exists | phones = '555-1, 555-2', or columns phone1, phone2, phone3 |
A child table customer_phones |
| 2NF | 1NF + every non-key column depends on the whole key (no partial dependency on part of a composite key) | In order_lines(order_id, sku, product_name, qty), product_name depends on sku alone |
Move product_name to products(sku) |
| 3NF | 2NF + no transitive dependencies (non-key → non-key) | orders(id, customer_id, customer_email): customer_email depends on customer_id |
Keep the email only in customers |
| BCNF | Every determinant is a candidate key (a stricter 3NF) | Rare edge cases with overlapping candidate keys | Decompose further |
| 4NF / 5NF | No multi-valued / join dependencies | Independent multi-valued facts in one table | Separate tables |
The informal summary (Bill Kent): every non-key attribute must provide a fact about the key (1NF), the whole key (2NF), and nothing but the key (3NF).
Unnormalised: orders_flat(order_id, customer_email, customer_name, sku, product_name, qty)
customers(id PK, email UNIQUE, name)
products(sku PK, name)
orders(id PK, customer_id FK → customers)
order_lines(order_id FK, sku FK, qty, PK(order_id, sku))
When to denormalise
Normalised schemas optimise writes and integrity. Reads sometimes need joins and aggregations that become expensive at scale. Deliberate denormalisation trades redundancy for read speed:
- Snapshots that should be copied: an order line stores
unit_price_centsandproduct_nameas of the purchase. That's not redundancy: the price at purchase time is a different fact from the current price. - Derived and aggregate columns:
orders.total_cents(the sum of lines),posts.comment_count. They must be maintained (in the same transaction, by triggers, or by recomputation) and checked. - Materialised views and read models (CQRS, chapter 61) keep the normalised source of truth and build query-optimised copies.
- JSON columns for genuinely document-shaped, rarely queried-by-field data (chapter 56).
- Analytical/OLAP schemas (star schemas: fact tables plus denormalised dimensions) are designed for reads.
Rule: normalise first (to 3NF), then denormalise specific, measured hot paths, with a mechanism that keeps the copies consistent.
Mapping the model to code
The relational model and object or struct models don't match perfectly (the object-relational impedance mismatch): object graphs versus flat relations, identity versus key equality, inheritance versus tables, collections versus foreign keys, and navigation versus joins. Vol. 3 ch. 49 covered ORMs and SQL-first tools. The design principle:
Design the schema for integrity and the access patterns you need, then map code to it, not the other way round.
Schemas outlive application code: databases are typically read by several services, reports and tools over decades, so constraints, names and types are worth getting right.
Lab: modelling mistakes, measured
PostgreSQL 16 driven from Python (psycopg) on a 2-core machine. Each experiment is a schema or type decision that looks harmless on day one.
Experiment 1: NOT IN meets a NULL
CREATE TABLE banned(name text); INSERT INTO banned VALUES ('Vada'), (NULL);
SELECT name FROM d WHERE name NOT IN (SELECT name FROM banned);
SELECT name FROM d WHERE NOT EXISTS (SELECT 1 FROM banned b WHERE b.name = d.name);
NOT IN (banned list containing a NULL): [] | NOT EXISTS: ['Masala dosa', 'Idli']
x NOT IN (a, NULL) means x <> a AND x <> NULL, and x <> NULL is unknown, so the whole condition is never true: one NULL in the subquery made the query return nothing, silently. NOT EXISTS compares row by row and ignores the NULL. Prefer NOT EXISTS for anti-joins (it's also what the planner handles best), and declare columns NOT NULL unless absence is genuinely meaningful.
Experiment 2: money in floating point
A million payments of ₹0.10, stored three ways:
sum as double precision = 100000.000000298 | numeric = 100000.00 | bigint paise = 10000000
0.10 has no exact binary representation (Volume 1 chapter 6), so a million additions drifted by three ten-millionths of a rupee. Tiny, but enough to fail reconciliation against a bank statement, and errors compound through tax and discount calculations. Use numeric(p, s) (exact decimal, slower and larger) or integers in the smallest unit (bigint paise, fast and exact). Never real, double precision or money (locale-dependent formatting).
Experiment 3: what types cost
bytes: smallint 2, int 4, bigint 8, numeric 1.5 10, numeric 123456789.12 14, timestamptz 8, uuid 16, text 'Masala dosa' 15, boolean 1
Every row also carries a 23-byte header plus alignment padding (chapter 58), so column order and type width matter on billion-row tables, but on most tables correctness dominates: int overflows at 2.1 billion (use bigint for ids and counters that grow), text is as fast as varchar(n) in PostgreSQL (use a CHECK for length rules), and numeric costs more than integers.
Experiment 4: timestamps with and without time zones
The same moment, 10:00 in India, stored as timestamp and as timestamptz, read by sessions in two time zones:
session time zone UTC : ('2026-10-29 10:00:00', '2026-10-29 04:30:00+00')
session time zone America/New_York : ('2026-10-29 10:00:00', '2026-10-29 00:30:00-04')
timestamp (without time zone) stored the wall-clock digits "10:00" and forgot where they came from, so every reader assumes their own zone: a New York service would think the order was placed at 10:00 New York time, nine and a half hours off. timestamptz stored an absolute instant (internally UTC) and displays it in each session's zone. Store events as timestamptz; use timestamp (plus a separate zone column) only for future local-time intentions like "open at 08:00 every day", whose UTC instant depends on daylight-saving rules.
Experiment 5: a foreign key without an index on the child
Deleting 200 parents, which cascades to 100,000 child rows out of a million:
child foreign key unindexed: 8862 ms
child foreign key indexed : 189 ms
PostgreSQL automatically indexes primary keys and unique constraints, but not the referencing column of a foreign key. Every delete of a parent (and every update of its key) must find the children, and without an index that's a scan of the whole child table per parent row: 47× slower here, and it holds locks the whole time. Index foreign-key columns that are used for joins or for deleting parents (most of them).
Experiment 6: choosing a primary key type
A million inserts in arrival order, each into a fresh table:
bigint identity : 2199 ms | index 22.5 MB | leaf pages 90% full
uuid v4 (random) : 4253 ms | index 39.9 MB | leaf pages 71% full
uuid v7, random within a millisecond : 1975 ms | index 44.0 MB | leaf pages 65% full
uuid v7, monotonic counter : 1384 ms | index 31.6 MB | leaf pages 90% full
Random UUIDv4 keys land anywhere in the B-tree, so inserts touch random pages (fine while the index fits in memory, painful when it doesn't) and pages split in the middle, leaving them about 70% full: the slowest load and an index 77% larger than bigint's. UUIDv7 puts a millisecond timestamp first, so new keys go to the right-hand edge of the index like a sequence, but only if values are also ordered within each millisecond: with random low bits, hundreds of keys per millisecond still caused mid-page splits and the largest index of all. RFC 9562's monotonic counter fixed that (90% full, fastest load). UUIDs are worth their 16 bytes when ids must be generated by clients or across services without coordination, or must not reveal counts; PostgreSQL 18 adds a built-in uuidv7() that is monotonic within a session.
Try it yourself
- Rewrite experiment 1's query with
LEFT JOIN … WHERE b.name IS NULLand compare plans withEXPLAIN. - Add
ON DELETE RESTRICTto experiment 5's foreign key and try the delete. When isCASCADEdangerous? - Repeat experiment 6 with 20 million rows and
shared_buffersset to 128 MB. How does the UUIDv4 load time grow compared with the others? - Model the café's opening hours (different per weekday, with holiday exceptions) and justify each type you choose.
Revision sheet: the relational model
Key ideas
- Relational model (Codd, 1970): data as relations (sets of tuples) with typed attributes; data independence from physical storage; declarative queries.
- Keys: candidate keys, the chosen primary key, surrogate vs natural keys, composite keys;
UNIQUEfor alternate keys. - Relationships: one-to-many (foreign key on the many side), many-to-many (junction table), one-to-one.
- Integrity:
NOT NULL,UNIQUE,CHECK,FOREIGN KEYwith referential actions (RESTRICT,NO ACTION,CASCADE,SET NULL,SET DEFAULT), exclusion constraints, deferrable constraints. - NULL: unknown, three-valued logic;
IS [NOT] DISTINCT FROM; aggregates skip NULLs;NOT INpitfall. - Normal forms: 1NF (atomic values), 2NF (no partial dependency on a composite key), 3NF/BCNF (every determinant is a key), 4NF/5NF (multi-valued and join dependencies); anomalies as the motivation.
- Denormalisation: deliberate redundancy (snapshots like order-time prices, caches, read models, materialised views) with a mechanism to keep it correct.
- Types: integers for counts and ids (
bigintfor growth),numericor integer minor units for money,timestamptzfor instants,textwith checks,uuid(prefer v7),jsonbfor genuinely schemaless parts, enums vs lookup tables.
Numbers to remember
- Lab: one NULL made
NOT INreturn nothing; a million float additions of 0.10 drifted by 3×10⁻⁷; an unindexed foreign key made a cascading delete 47× slower; UUIDv4 keys loaded about 2× slower than a monotonic UUIDv7 with a 26% larger index. intmax ≈ 2.1 billion; row header 23 bytes;uuid16 bytes,bigint8.
Pitfalls
- Spreadsheet-shaped tables; comma-separated lists in a column; entity-attribute-value designs.
- Natural keys that change; missing
UNIQUEon real-world identifiers. - Nullable columns by default;
NOT INwith nullable subqueries. - Floats for money;
timestampwithout time zone for events;intids that overflow. - Foreign keys without indexes;
ON DELETE CASCADEon large or important hierarchies. - Denormalising without a plan to keep copies consistent.
Glossary
- Relation / tuple / attribute: table / row / column, in the model's terms.
- Functional dependency: A → B when A's value determines B's.
- Candidate key: a minimal set of attributes that uniquely identifies rows.
- Junction table: a table representing a many-to-many relationship.
- Referential action: what happens to children when a parent is deleted or updated.
- Three-valued logic: true, false and unknown.