Sub topic 4
Natural versus surrogate keys
This chapter assumes you can write CREATE TABLE, know that a primary key is UNIQUE and NOT NULL, and have seen a foreign key with REFERENCES. It covers how to choose what a primary key is made of. Examples use PostgreSQL syntax.
The choice
Every table needs a primary key. Often more than one column set could serve, because each one uniquely identifies a row. These are the candidate keys. You pick one as the primary key, and you have two broad options.
- A natural key is built from data that already exists in the real world and means something to users. Examples are an email address, an ISBN, an ISO country code, or a national tax number.
- A surrogate key is a value the database or application invents only to identify the row. It carries no business meaning. Examples are an auto-incrementing integer or a UUID.
The customers table from the topic plan uses both. customer_id is the surrogate primary key. email is a natural candidate key that stays unique but is not the primary key.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);Choosing the surrogate key as the primary key does not remove the natural one. The UNIQUE constraint on email still enforces the business rule that no two customers share an address.
Why natural keys look attractive
A natural key has real advantages.
- It is already in the data, so there is no extra column.
- It is readable. A row with
country_code = 'DE'explains itself in a query or a log line. - A foreign key to it can avoid a join. If
addresses.country_codereferencescountries (country_code), the codeDEis already in the child row. - The uniqueness rule you wanted anyway is enforced by the primary key itself.
For small, stable reference data, natural keys work well.
CREATE TABLE countries (
country_code CHAR(2) PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE addresses (
address_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
street VARCHAR(200) NOT NULL,
country_code CHAR(2) NOT NULL REFERENCES countries (country_code)
);Why natural keys fail
The trouble is that real-world data changes, repeats, and sometimes does not exist. These are the failure modes to check for.
Values change
People change email addresses. Companies rename products and reissue part numbers. If the primary key changes, every foreign key that references it must change too. You can allow that with ON UPDATE CASCADE, but one key change then rewrites rows in every child table, and any external system that stored the old value is left stale.
Values are not as unique as they seem
Names are not unique. Email addresses are shared in some families and teams. Some national identifiers are reused, reissued, or missing for some people. A rule that holds in your test data can fail on real data.
Values may be unknown at insert time
A primary key cannot be NULL. If a natural key is only known later, such as a tax number collected after sign-up, it cannot be the primary key. It can still be a nullable UNIQUE column, because PostgreSQL allows multiple NULL values in a unique column.
Values are wide or sensitive
A key is copied into every foreign key column and every index that includes it. A 255-character email repeated in millions of order rows costs storage and slows comparisons. Using personal data as a key also spreads it into every table that references it, which makes deleting or masking it harder.
Composite natural keys grow unwieldy
A natural key may need several columns to be unique. Every child table must then carry all of them, and every join must compare all of them.
Why surrogate keys are the common default
A surrogate key avoids those problems.
- It never changes, because it has no meaning to change with.
- It is small. A 4-byte or 8-byte integer is cheap to store, index, and compare.
- It is always known the moment the row exists.
- Child tables carry one column, which keeps foreign keys and joins simple.
Surrogate keys have costs of their own.
- They add a column and often an extra index, since you still need the
UNIQUEconstraint on the natural identifier. - They are opaque.
customer_id = 4821tells you nothing when you read a log. - They do not prevent duplicates. Without a
UNIQUEconstraint on the natural identifier, you can insert the same customer twice with two different ids.
Choosing a surrogate type
The most common choices differ in size, ordering, and exposure.
| Type | Typical size | Strengths | Trade-offs |
|---|---|---|---|
| `INTEGER` identity | 4 bytes | Compact, fast, ordered by insertion | Runs out near 2.1 billion values; guessable |
| `BIGINT` identity | 8 bytes | Practically unlimited range | Twice the size of `INTEGER` |
| `UUID` | 16 bytes | Can be generated anywhere without coordination | Larger indexes; random values scatter inserts across the index |
For a table that could plausibly pass two billion rows over its lifetime, start with BIGINT. Changing an INTEGER key type later means rewriting the table and every foreign key that references it.
Sequential integers are guessable. If /orders/1042 is a public URL, a visitor can try /orders/1043. Hiding the id is not a substitute for an authorization check, but you may prefer a UUID, or a separate random public identifier, for values exposed outside your system.
A rule of thumb
- Use a surrogate primary key for tables that represent business entities that change over time: customers, orders, products, employees.
- Keep a
UNIQUE NOT NULLconstraint on any natural identifier that must not repeat. - Consider a natural primary key for small, stable lookup tables where the code is a recognized standard, such as ISO country codes.
- In a junction table, use a composite key built from the two foreign keys instead of adding an id. Composite keys are covered in a later chapter.
Checking your choice
To see whether an existing natural key would have been safe, look for duplicates and nulls in real data before you commit to it.
SELECT email, COUNT(*) AS copies
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;If this returns rows when run on email values in a raw import table, email cannot be a primary key or a unique column without cleaning the data first.
Exercise
A products table uses the manufacturer's sku (for example AB-1029) as its primary key. Marketing announces that all SKUs will be renamed next quarter. Orders reference products through order_items.product_id. Give two problems this causes, and describe a redesign that fixes them.
Show answer
First, every order_items row that references a renamed SKU must be updated too. This needs ON UPDATE CASCADE or a manual update, and it rewrites many child rows. Second, any external system, report, or log that stored the old SKU no longer matches. The redesign adds a generated surrogate key, such as product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, makes order_items.product_id reference it, and keeps sku VARCHAR(20) NOT NULL UNIQUE so SKUs still cannot repeat. A rename then changes one cell in one row.
Exercise
A teammate removes UNIQUE from customers.email because customer_id is already the primary key. What can now happen, and what query would show it?
Show answer
The same email address can be inserted for several customers, each with a different customer_id. The primary key only guarantees that ids are distinct, not that the person is. This query lists the duplicates: SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1;. The fix is to clean the duplicates and restore UNIQUE (email).