skip to content

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.

key =
ada.sql
  1. 1UPDATE customers SET email = 'ada@lovelace.dev' WHERE email = 'ada@example.com';
  2. 2SELECT id, customer_email, total FROM orders ORDER BY id;
ERROR: update or delete on table "customers" violates foreign key constraint "orders_customer_email_fkey" on table "orders"SQLSTATE 23503

the key is referenced, and the foreign key says NO ACTION: three orders still point at the old email, so the update fails.

real output, postgres 18.6 (PGlite 0.5.12) · email-key
Ada changes her email. pick the key. with email as the key and a plain foreign key, the update is refused, because orders still point at the old value. with ON UPDATE CASCADE it succeeds by rewriting every order. with a surrogate id, orders never held the email in the first place.

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:

sqlempty db
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');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · ERROR 23505
ERROR 23505: duplicate key value violates unique constraint "products_pkey"
DETAIL: Key (sku)=(TEA-01) already exists.
#4 · ERROR 23502
ERROR 23502: null value in column "sku" of relation "products" violates not-null constraint
DETAIL: Failing row contains (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 vocabulary, as a tree. every candidate key is a superkey with nothing to spare; the primary key is the one you chose.

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":

sqldb=shop
SELECT conname, pg_get_constraintdef(oid) AS def
FROM pg_constraint
WHERE conrelid = 'order_items'::regclass AND contype IN ('p', 'f')
ORDER BY conname;
output, from postgres 18.6
SELECT 3
connamenamedeftext
order_items_order_id_fkeyFOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
order_items_pkeyPRIMARY KEY (order_id, line_no)
order_items_product_id_fkeyFOREIGN KEY (product_id) REFERENCES products(id)
(3 rows)

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.

predict the output
sql
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;
sqlempty db · session dupes
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · INSERT 0 1
#4 · SELECT 2
idint4emailtextnametext
1ada@example.comAda Lovelace
2ada@example.comAda Lovelace
(2 rows)

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:

sqlempty db · session dupes
continues session dupes (1 earlier block run first)
ALTER TABLE people ADD UNIQUE (email);
output, from postgres 18.6
ERROR 23505: could not create unique index "people_email_key"
DETAIL: Key (email)=(ada@example.com) is duplicated.

natural or surrogate

natural key (email, ISBN, sku)surrogate key (identity, uuid)
meaningreadable: an order line says TEA-01opaque: you join to find out what 1 is
changethe world changes it, and every reference follows (cascade, or a migration)never changes, by construction
sizewhatever the value is; text keys are long and copied into every referencing row and index4 or 8 bytes for an integer, 16 for a uuid
duplicatesthe key itself stops themneeds a separate UNIQUE on the natural key, or duplicates go in
when it fitscodes that really are stable: country codes, currency codes, a sku you controlalmost every entity table people edit

the sizes, measured:

sqlempty db
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 4
keytextbytesint4
int4
bigint8
uuid16
text, an email25
(4 rows)
int4 bytes
bigint8 bytes
uuid16 bytes
text, an email25 bytes
bytes per key value, from the block above. every foreign key column and every index entry pointing at the table pays this per row. (the stored email is 24 characters plus a 1-byte length header.)

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.