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:
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 purposeError: UNIQUE constraint failed: customers.emailA common pattern is natural keys for small, standard code tables and surrogate keys for business entities such as customers and orders.
-- 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