Sub topic 4
Natural versus Surrogate Keys
This chapter assumes you know how to create tables, choose column types, and use basic INSERT, UPDATE, and DELETE statements. A key is a column, or group of columns, that identifies a row. The main design choice is whether that key should describe a real business value or be an independent generated value.
Natural keys
A natural key is a value that already exists in the real-world data and uniquely identifies a row. Examples include:
- A two-letter country code such as
US. - An ISBN for a book.
- An employee number assigned by an organization.
- An email address, when the application guarantees that it is unique and stable.
A natural key can make data easy to recognize. However, it must remain unique and must not change unexpectedly. Real-world values often fail one of these tests. An email address can change. A business may revise an employee-number format. A supposedly unique identifier may later be reused or corrected.
A natural key is a candidate key when it is both unique and minimal. A table can have several candidate keys, but it has one chosen primary key. Other candidate keys can receive UNIQUE constraints.
Surrogate keys
A surrogate key is an artificial identifier created only for the database. It has no business meaning. An integer identity column and a generated UUID are common surrogate keys.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);Here, customer_id is the surrogate primary key. The email address is a natural candidate key protected by UNIQUE. Other tables can reference customer_id even if the customer changes their email address.
Surrogate keys usually keep foreign keys small and stable. They also avoid exposing business information in URLs or other identifiers. Their weakness is that the number itself tells you nothing, so you still need business constraints such as UNIQUE to prevent duplicate real-world entities.
Choosing between them
Use a natural primary key when the value is:
- Already guaranteed to be unique.
- Stable for the row's entire lifetime.
- Small enough for frequent references.
- Safe to expose and use across systems.
Use a surrogate primary key when the natural value can change, contains private information, is large, or depends on an external system. You can still preserve the natural identifier with a unique constraint.
| Choice | Main benefit | Main risk |
|---|---|---|
| Natural key | Meaningful and avoids an extra identifier | It may change or stop being unique |
| Surrogate key | Stable references and simple relationships | It has no meaning without business constraints |
Exercise
A customer email address is currently unique but customers can change it. Should it usually be the primary key?
Show answer
No. Use a stable surrogate primary key and put a UNIQUE constraint on the email address if it must remain unique.