primary keys, natural and surrogate
what makes a row itself. composite keys, and the email address that changed.
- address
- everything.design.keys
- part
- part 7, schema design
- chapter
- chapter 2 of 13
- reading time
- 8 min
a primary key is the column (or columns) that makes a row itself: UNIQUE plus NOT NULL, one per table, and the thing every foreign key points at. a table can have several candidate keys; you pick one and put UNIQUE on the rest.
a natural key comes from the world (an email, an ISBN), a surrogate key is a number the database makes up. natural keys change, and every reference has to change with them. so the usual answer is: a surrogate primary key, and a UNIQUE constraint on the natural one.
the picture
you know how every app has a users table keyed by an auto-increment id, and someone always asks "why not just use the email? it's unique already"? it is unique. it just isn't permanent: people change emails, and a key gets copied into every table that points at it.
think of a library. a book's ISBN identifies it (a natural key), but the library also stamps its own accession number inside the cover (a surrogate). when a publisher reissues the book with a corrected ISBN, the catalogue changes one card. the loan records, which only ever wrote down the stamp, don't change at all.
- 1UPDATE customers SET email = 'ada@lovelace.dev' WHERE email = 'ada@example.com';
- 2SELECT id, customer_email, total FROM orders ORDER BY id;
the key is referenced, and the foreign key says NO ACTION: three orders still point at the old email, so the update fails.
cascade "works", and it's the honest version of the problem: one UPDATE in customers became three in orders, each a new row version with new index entries (an UPDATE is an INSERT). on a customer with ten thousand orders, in a table with five foreign keys pointing at it, changing an email is a big write holding row locks the whole time.
what a primary key promises
PRIMARY KEY is exactly UNIQUE plus NOT NULL, and postgres builds a unique b-tree index to enforce it. both halves fail out loud:
CREATE TABLE products (sku text PRIMARY KEY, name text NOT NULL);
INSERT INTO products VALUES ('TEA-01', 'assam tea');
INSERT INTO products VALUES ('TEA-01', 'darjeeling');
INSERT INTO products VALUES (NULL, 'mystery tea');the first error names the index and the duplicate value; the second, the null column. there can be only one primary key per table. any other candidate key is spelled UNIQUE plus NOT NULL on its columns, and behaves the same way (foreign keys can point at it too).
- any set of columns that's unique: (id, email, name) counts
- ├── a minimal superkey: drop any column and it stops being unique
- │ ├── primary keythe one candidate you pick. NOT NULL, one per table, what FKs point at
- │ └── alternate keyevery other candidate: UNIQUE NOT NULL
- └── composite keya key with more than one column, like (order_id, line_no)
the candidate keys come from the meaning of the columns, via functional dependencies: a set is a key when it determines every other column and no smaller set does.
composite keys
when the thing a row describes is a pair, the key is the pair. shop's order_items has no id of its own; a line is "line 2 of order 5":
SELECT conname, pg_get_constraintdef(oid) AS def
FROM pg_constraint
WHERE conrelid = 'order_items'::regclass AND contype IN ('p', 'f')
ORDER BY conname;| connamename | deftext |
|---|---|
| order_items_order_id_fkey | FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE |
| order_items_pkey | PRIMARY KEY (order_id, line_no) |
| order_items_product_id_fkey | FOREIGN KEY (product_id) REFERENCES products(id) |
the school's enrollments are keyed by (student_id, course_code, term), because the same student can retake a course in a later term. a composite key costs nothing extra to store (those columns are there anyway) and states a rule a surrogate wouldn't: the same student can't enroll twice in one course in one term.
two things to know. the column order of a composite key is the column order of its index, so (student_id, course_code, term) serves "all of student 7's enrollments" and not "everyone in CS101" (composite indexes). and anything referencing it has to carry all three columns. that's fine for a leaf table; for a table many others point at, it's the argument for a surrogate.
CREATE TABLE people (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
name text NOT NULL
);
INSERT INTO people (email, name) VALUES ('ada@example.com', 'Ada Lovelace');
INSERT INTO people (email, name) VALUES ('ada@example.com', 'Ada Lovelace');
SELECT count(*) FROM people;CREATE TABLE people (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
name text NOT NULL
);
INSERT INTO people (email, name) VALUES ('ada@example.com', 'Ada Lovelace');
INSERT INTO people (email, name) VALUES ('ada@example.com', 'Ada Lovelace');
SELECT id, email, name FROM people ORDER BY id;| idint4 | emailtext | nametext |
|---|---|---|
| 1 | ada@example.com | Ada Lovelace |
| 2 | ada@example.com | Ada Lovelace |
the surrogate is the row's name; the natural key still needs its constraint. trying to add it now finds the duplicate you already let in:
ALTER TABLE people ADD UNIQUE (email);natural or surrogate
| natural key (email, ISBN, sku) | surrogate key (identity, uuid) | |
|---|---|---|
| meaning | readable: an order line says TEA-01 | opaque: you join to find out what 1 is |
| change | the world changes it, and every reference follows (cascade, or a migration) | never changes, by construction |
| size | whatever the value is; text keys are long and copied into every referencing row and index | 4 or 8 bytes for an integer, 16 for a uuid |
| duplicates | the key itself stops them | needs a separate UNIQUE on the natural key, or duplicates go in |
| when it fits | codes that really are stable: country codes, currency codes, a sku you control | almost every entity table people edit |
the sizes, measured:
CREATE TABLE k (i int, b bigint, u uuid, e text);
INSERT INTO k VALUES (42, 42, '0195f0a6-7c3e-7b12-9d1e-3f5a2b1c4d5e', 'ada.lovelace@example.com');
SELECT x.key, x.bytes
FROM k, LATERAL (VALUES ('int', pg_column_size(i)), ('bigint', pg_column_size(b)),
('uuid', pg_column_size(u)), ('text, an email', pg_column_size(e))) AS x(key, bytes)
ORDER BY x.bytes, x.key;| keytext | bytesint4 |
|---|---|
| int | 4 |
| bigint | 8 |
| uuid | 16 |
| text, an email | 25 |
bigint or uuid for the surrogate is its own question, with real numbers: random uuids scatter inserts across the whole index, uuidv7 doesn't, and bigint is half the size of either. identity columns and uuids measures it leaf by leaf. the short version: a bigint identity unless ids have to be generated outside the database or unguessable in a URL, then uuidv7.
keylines
- a primary key is UNIQUE plus NOT NULL, one per table, what foreign keys point at.
- candidate keys come from the meaning of the columns; pick one, UNIQUE the rest.
- natural keys change, and every reference changes with them.
- a surrogate key needs a UNIQUE on the natural key, or duplicates walk in.
- composite keys are right when the row is a pair; their column order is the index's.