← Back to SQL, page 10

sql-0185 · Easy fresher

Natural key or surrogate key: how do they differ, and when is each a good fit? Give an example of each.

A natural key comes from the data itself, such as an ISO country code or an email address. A surrogate key is a meaningless generated value, such as an auto-increment integer or a UUID. Natural keys can change or turn out not to be unique; surrogate keys are stable but need a separate UNIQUE on the natural attributes.

Full answer

Natural keys work well when the value is stable, short and truly unique: ISO country codes ('IN', 'FR'), currency codes ('EUR') or airport codes. Joins read clearly, and a lookup table needs no extra id.

They cause trouble when reality changes. Emails change, people share names, and national id numbers are not universal and are sensitive data. If a natural key changes, every referencing row must change too.

A surrogate key avoids those updates. The cost is that it does not stop duplicates of the real-world thing, so keep a UNIQUE constraint on the natural attributes:

sql
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
INSERT INTO customers (email) VALUES ('ana@example.com');
INSERT INTO customers (email) VALUES ('ana@example.com');
-- error on purpose
text
Error: UNIQUE constraint failed: customers.email

A common pattern is natural keys for small, standard code tables and surrogate keys for business entities such as customers and orders.

sql
-- error on purpose
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
INSERT INTO customers (email) VALUES ('ana@example.com');
INSERT INTO customers (email) VALUES ('ana@example.com');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Natural keys come from the data
  • Surrogate keys are generated and meaningless
  • Natural keys can change or collide
  • Keep a UNIQUE on natural attributes when using surrogates

Common mistakes

  • Using email as a primary key
  • Using a surrogate key without any uniqueness on the real identifier

Follow-ups

  • Would you use a natural key for a country table?
  • How do key changes affect foreign keys?

Tips

  • Give one good and one bad natural key