Database Natural and Surrogate Keys
What you will learn
- The difference between a natural key and a surrogate key
- The strengths and weaknesses of each
- Why keys must be stable
- A sensible default for new tables
1. Two kinds of key
- A natural key is a value that already exists in the real world and identifies the thing: a book's ISBN, a country code, a course code like
MATH101, a username. - A surrogate key is a value the database invents only to identify the row, usually an auto-numbered integer. It means nothing outside the database.
| Natural key | Surrogate key | |
|---|---|---|
| Source | real world | invented by the database |
| Example | MATH101 |
17 |
| Meaning | yes | none |
| Can it change? | possibly | no, if you never edit it |
| Readable | yes | no |
2. A natural key that changes
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It creates small tables of its own in your browser's copy; run the examples from top to bottom, and press Reset data to start again.
Suppose codes identify things, and other tables point to those codes. (REFERENCES creates a link between tables, a foreign key, covered in lesson 3.1. The sample databases enforce it.)
The Shop runs promotions, each identified by its code. Customers' uses of a promotion point to that code:
CREATE TABLE promos (code TEXT PRIMARY KEY NOT NULL, title TEXT);
CREATE TABLE promo_uses (
customer_id INTEGER REFERENCES customers (customer_id),
promo_code TEXT REFERENCES promos (code)
);
INSERT INTO promos VALUES ('SPRING10', 'Spring sale');
INSERT INTO promo_uses VALUES (1, 'SPRING10'), (2, 'SPRING10'), (3, 'SPRING10');
(3 rows changed)
The shop renames the code. The database refuses, because three rows still use the old one:
UPDATE promos SET code = 'SPR10' WHERE code = 'SPRING10';
IntegrityError: FOREIGN KEY constraint failed
SELECT * FROM promo_uses ORDER BY customer_id;
customer_id promo_code
----------- ----------
1 SPRING10
2 SPRING10
3 SPRING10
(3 rows)
The Bank sells account products, each identified by its code. Accounts point to the code of their product:
CREATE TABLE products (code TEXT PRIMARY KEY NOT NULL, title TEXT);
CREATE TABLE account_products (
account_id INTEGER REFERENCES accounts (account_id),
product_code TEXT REFERENCES products (code)
);
INSERT INTO products VALUES ('SAV-STD', 'Standard savings');
INSERT INTO account_products VALUES (1, 'SAV-STD'), (2, 'SAV-STD'), (3, 'SAV-STD');
(3 rows changed)
The bank renames the code. The database refuses, because three rows still use the old one:
UPDATE products SET code = 'SAV-1' WHERE code = 'SAV-STD';
IntegrityError: FOREIGN KEY constraint failed
SELECT * FROM account_products ORDER BY account_id;
account_id product_code
---------- ------------
1 SAV-STD
2 SAV-STD
3 SAV-STD
(3 rows)
The School has clubs, each identified by its code. Students' memberships point to the code:
CREATE TABLE clubs (code TEXT PRIMARY KEY NOT NULL, title TEXT);
CREATE TABLE club_members (
student_id INTEGER REFERENCES students (student_id),
club_code TEXT REFERENCES clubs (code)
);
INSERT INTO clubs VALUES ('CHESS', 'Chess club');
INSERT INTO club_members VALUES (1, 'CHESS'), (2, 'CHESS'), (3, 'CHESS');
(3 rows changed)
The school renames the code. The database refuses, because three rows still use the old one:
UPDATE clubs SET code = 'CHESS1' WHERE code = 'CHESS';
IntegrityError: FOREIGN KEY constraint failed
SELECT * FROM club_members ORDER BY student_id;
student_id club_code
---------- ---------
1 CHESS
2 CHESS
3 CHESS
(3 rows)
You would have to update every table that mentions the code, in step. The more a key means in the real world, the more reasons it has to change.
3. The surrogate version
Give each row a meaningless number, and keep the code as an ordinary (but unique) column:
CREATE TABLE promos2 (id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, title TEXT);
CREATE TABLE promo_uses2 (
customer_id INTEGER REFERENCES customers (customer_id),
promo_id INTEGER REFERENCES promos2 (id)
);
INSERT INTO promos2 (code, title) VALUES ('SPRING10', 'Spring sale');
INSERT INTO promo_uses2 VALUES (1, 1), (2, 1), (3, 1);
UPDATE promos2 SET code = 'SPR10' WHERE id = 1;
SELECT u.customer_id, p.code
FROM promo_uses2 u JOIN promos2 p ON p.id = u.promo_id
ORDER BY u.customer_id;
customer_id code
----------- -----
1 SPR10
2 SPR10
3 SPR10
(3 rows)
CREATE TABLE products2 (id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, title TEXT);
CREATE TABLE account_products2 (
account_id INTEGER REFERENCES accounts (account_id),
product_id INTEGER REFERENCES products2 (id)
);
INSERT INTO products2 (code, title) VALUES ('SAV-STD', 'Standard savings');
INSERT INTO account_products2 VALUES (1, 1), (2, 1), (3, 1);
UPDATE products2 SET code = 'SAV-1' WHERE id = 1;
SELECT a.account_id, p.code
FROM account_products2 a JOIN products2 p ON p.id = a.product_id
ORDER BY a.account_id;
account_id code
---------- -----
1 SAV-1
2 SAV-1
3 SAV-1
(3 rows)
CREATE TABLE clubs2 (id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, title TEXT);
CREATE TABLE club_members2 (
student_id INTEGER REFERENCES students (student_id),
club_id INTEGER REFERENCES clubs2 (id)
);
INSERT INTO clubs2 (code, title) VALUES ('CHESS', 'Chess club');
INSERT INTO club_members2 VALUES (1, 1), (2, 1), (3, 1);
UPDATE clubs2 SET code = 'CHESS1' WHERE id = 1;
SELECT m.student_id, c.code
FROM club_members2 m JOIN clubs2 c ON c.id = m.club_id
ORDER BY m.student_id;
student_id code
---------- ------
1 CHESS1
2 CHESS1
3 CHESS1
(3 rows)
Now renaming the code is one UPDATE on one row. The rows that use the code point at the number 1, which never changed, and the join shows the new code for all three. (JOIN is explained in lesson 4.5.)
The sample databases follow this pattern too. Their tables have a surrogate ..._id key, and the real-world identifier is kept UNIQUE:
SELECT name, "unique" FROM pragma_index_list('products');
SELECT product_id, sku, name FROM products ORDER BY product_id LIMIT 3;
name unique
--------------------------- ------
sqlite_autoindex_products_1 1
(1 row)
product_id sku name
---------- -------- ----------------
1 SKU-0001 Steel pan
2 SKU-0002 Ceramic mug
3 SKU-0003 Wooden spoon set
(3 rows)
SELECT name, "unique" FROM pragma_index_list('branches');
SELECT branch_id, name, city FROM branches ORDER BY branch_id LIMIT 3;
name unique
--------------------------- ------
sqlite_autoindex_branches_1 1
(1 row)
branch_id name city
--------- --------- -------
1 Central Lisbon
2 Riverside Toronto
3 Harbour Osaka
(3 rows)
SELECT name, "unique" FROM pragma_index_list('courses');
SELECT course_id, code, title FROM courses ORDER BY course_id LIMIT 3;
name unique
-------------------------- ------
sqlite_autoindex_courses_1 1
(1 row)
course_id code title
--------- ------- ----------------------
1 MATH101 Foundations of Algebra
2 MATH201 Geometry
3 MATH301 Statistics
(3 rows)
The index named sqlite_autoindex_... is how SQLite enforces the UNIQUE rule; the 1 means it is unique.
4. Weighing them up
Surrogate keys
- (+) Never change, because they mean nothing.
- (+) Short and fast to compare.
- (+) Work for every table, even where no good natural key exists.
- (-) Unreadable: you see
17, not what it is. - (-) Do not stop duplicates by themselves. Two rows can describe the same real course with different ids unless you also add a
UNIQUErule on the real-world identifier (lesson 2.6).
Natural keys
- (+) Readable and meaningful.
- (+) Uniqueness of the real-world thing is enforced automatically.
- (-) The real world changes its mind: people change emails and names; companies reuse codes.
- (-) Often long, or made of several columns.
- (-) Some "natural" keys are not really unique or not always present.
5. A safe default
For most tables: use a surrogate id as the primary key, and put a UNIQUE constraint on the natural identifier. You get stability and a guard against duplicates. Natural keys as primary keys are best kept for rare stable codes, such as a fixed list of country codes.
Worked example: members of a club
The club thinks of members by email. Design:
CREATE TABLE members (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
)
Other tables (payments, events attended) point to members.id. When Rina changes her email, one cell changes. Two members cannot register the same email because of UNIQUE. The club is made up.
Common mistakes
- Using a person's name or email as the primary key.
- Calling a number "unique" without checking. Phone numbers are shared, reused and mistyped.
- Giving the surrogate key a meaning (such as encoding the year in the number) and then depending on it.
- A surrogate key with no
UNIQUEon the real identifier, letting duplicates in.
Key takeaways
- A natural key comes from the real world; a surrogate key is an invented meaningless number.
- Keys that mean something may have to change, and changing a key ripples through every table that refers to it.
- A good default: surrogate
idas primary key plusUNIQUEon the natural identifier. - Never edit a surrogate key.
Practice
1. Is an ISBN a natural or a surrogate key?
Show answer
Natural: it exists in the real world and identifies the book.
2. Why did renaming the code fail in section 2?
Show answer
Other rows still referred to the old code, and the foreign key rule refused a change that would leave them pointing at nothing.
3. What is the main benefit of a surrogate key?
Show answer
It never needs to change because it carries no real-world meaning.
4. What problem can a surrogate key alone cause, and how do you prevent it?
Show answer
Duplicate real-world records with different ids. Add a UNIQUE constraint on the natural identifier.
5. Give an example of a natural identifier that could change.
Show answer
An email address or a phone number.
6. Which would you choose for a products table, and why?
Show answer
A surrogate id as primary key with UNIQUE on the product code, since codes can be reorganised while the id stays fixed.