Choosing Between Natural and Surrogate Keys

Every table needs a primary key. You can use a value that already exists in the real world, a natural key, or one the database makes up, a surrogate key. This page compares the two with simple examples and gives a verdict for common beginner tables.

Natural keys

A natural key is real information that already identifies something.

Examples: a country code such as FR, a product's printed code, an email address, a username.

CREATE TABLE countries (code TEXT PRIMARY KEY, name TEXT NOT NULL);

Pros:

Cons:

Surrogate keys

A surrogate key is a value with no meaning outside the database, usually a number the database generates.

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  username TEXT NOT NULL UNIQUE
);

Pros:

Cons:

Side by side

QuestionNatural keySurrogate key
Can it change?SometimesNo
Always available at insert?Not alwaysYes
Meaningful to humans?YesNo
Stops duplicate real-world items?YesOnly with an extra UNIQUE rule
Size in other tablesVariesSmall

Verdict for common tables

TableSuggested keyWhy
users, customers, membersSurrogate id plus UNIQUE on email or usernameEmails and usernames change
countries, currenciesNatural standard code can workCodes are short and stable
productsSurrogate id plus UNIQUE on product codeCodes may be reissued or changed
orders, posts, eventsSurrogate idNo natural identifier exists
linking tables such as enrolmentsThe pair of foreign keysThe pair is the natural identity

The popular combination

The most common beginner-friendly pattern is: a surrogate id as the primary key, plus a UNIQUE rule on the natural value. You get stability from the id and duplicate protection from the rule.

A note on privacy

Never use sensitive values, such as national identity numbers, as keys. Keys get copied into many tables, logs and URLs.

Practise the decision

Try the eight primary key scenarios, and record your choice with the primary key decision template.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site