Difficulty: Beginner
What is a surrogate key, how is it different from a natural key, and which would you choose as a primary key?
A surrogate key is a primary key generated by the system, such as an auto-increment integer or a UUID, that has no meaning outside the database. A natural key is a column, or set of columns, that already identifies the entity in the real world, like a PAN number, an email address or an ISBN. Most modern schemas use a surrogate primary key and still enforce the natural key with a UNIQUE constraint, getting stable joins and real-world uniqueness at the same time.
| Entity | Natural key candidate | Surrogate key |
|---|---|---|
| Customer | Email, phone number, PAN | customer_id BIGINT |
| Book | ISBN | book_id |
| Vehicle | Registration number | vehicle_id |
| Country | ISO code IN | country_id |
BIGINT is smaller and faster to compare and index than a 50-character email or a composite of three columns. This matters because the primary key is copied into every foreign key and, in InnoDB, into every secondary index.INR).(student_id, course_id) is a perfectly good primary key.BIGINT GENERATED ALWAYS AS IDENTITY in PostgreSQL (preferred over the older SERIAL), AUTO_INCREMENT in MySQL. Simple and compact but guessable, and hard to generate across many databases.Adding a surrogate key and forgetting the unique constraint on the natural key. Then the database happily stores two customers with the same email under different ids, and you get duplicate accounts. The surrogate key identifies the row; the unique constraint protects the business rule.
CREATE TABLE customers (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- surrogate
email TEXT NOT NULL,
phone TEXT,
pan_number CHAR(10),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_customers_email UNIQUE (email), -- natural key still enforced
CONSTRAINT uq_customers_pan UNIQUE (pan_number)
);
-- Child tables reference the compact, stable id
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id)
);
If a customer changes their email, only one row changes. Orders keep pointing at the same id.
Surrogate Key, Natural Key, Primary Key, Unique Constraint, Identity Column