Part 09 / Topic 4 of 7
Choosing keys
Every table needs a primary key — the column(s) that identify exactly one row, forever. The real decision is natural vs surrogate:
- A natural key is real data that happens to be unique: an email, a national ID, an ISBN.
- A surrogate key is a meaningless identifier the system generates:
customer_id 4.
Natural keys look attractive — no "extra" column — and then reality arrives: people change emails, countries reissue IDs, publishers recycle ISBNs. Because the primary key is copied into every referencing table, a changed natural key must be updated everywhere at once. Surrogate keys never change because they never meant anything. Default: surrogate key, with the natural candidate kept honest by a UNIQUE constraint — exactly shopdb's customers: customer_id primary, email unique.
Composite keys (several columns) are right where the row is a pairing — order_items (order_id, product_id).
For the surrogate itself, two mainstream choices:
bigint identity |
uuid |
|
|---|---|---|
| Size / index locality | 8 bytes, new rows cluster together | 16 bytes, random placement |
| Generated by | the database, in sequence | anywhere — app, offline device, other service |
| Guessable? | yes (sequential — don't expose as a secret) | no |
| Readability in debugging | pleasant | hostile |
Rule of thumb: bigint GENERATED ALWAYS AS IDENTITY inside one database; uuid when ids must be minted in several places at once or must not be guessable. (UUIDv7 — time-ordered — softens the locality cost; it landed as uuidv7() in PostgreSQL 18, one version past this course's 17.)
🧪 Quick quiz — answer from memory, then check.
- Why do natural primary keys hurt when the value changes?
- What is the keep-both default?
Show the answers
- The key is copied into every referencing table, so one change must propagate everywhere, atomically.
- Surrogate primary key + UNIQUE constraint on the natural candidate.
Done here? The practice set for Part 9 — 4 exercises with solutions — is on the part page.