Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

Choosing Keys: Natural, Surrogate and Composite

Pick primary keys that stay stable under real-world change, keep business identifiers unique, and map many-to-many relationships through junction tables with composite keys.

Contentsand lesson path

What you will learn

  • Map an ER model to tables with primary, foreign, natural and surrogate keys, including junction tables for many-to-many relationships.

Prerequisites: SQL Fundamentals

01. Why it matters

The entities and relationships are on paper now; keys are the first decision that turns them into tables. A key is how a row says I am this one — and how every other row says I point at that one.

Keys are also the decision you can least afford to get wrong. Change a column's type or add a nullable column and you have a routine migration. Change a primary key after other tables reference it and you must update every reference, in the right order, while writers are live. Key choices deserve deliberate thought at design time precisely because they are so sticky.

Three questions decide the shape of every table: what identifies a row (the primary key), which real-world identifiers must stay unique even though they are not the primary key, and how two entities meet in the middle when both sides say "many".

02. What a key must be

A column (or set of columns) can serve as a key only if it is:

  • Unique. Two rows never share the value; the database refuses the second insert.
  • Never missing. A key column cannot be NULL, because a missing value cannot identify anything.
  • Stable. The value does not change over the row's life. This is the requirement real-world data breaks most often.
  • Minimal. Drop any column from a composite key and it stops being unique; adding "just in case" columns weakens it.

A table often has more than one candidate that passes: a customers table might offer email address and phone number. Pick one as the primary key; keep the others as UNIQUE constraints so the database still enforces them. The others are not wasted — a foreign key may reference any primary key or unique column.

03. Natural keys, surrogate keys and the safe default

A natural key is an identifier from the domain itself: an email address, a product SKU, a country's ISO code, a national insurance number. It carries meaning, which is its charm and its danger. People can mis-type it, the format can be revised, and the thing it names can change it — customers change email addresses. When the key changes, every row that references it must change in the same instant.

A surrogate key is a value the database generates purely to identify the row, with no meaning in the domain. In PostgreSQL the standard form is an identity column: bigint GENERATED ALWAYS AS IDENTITY, which hands out 1, 2, 3 and refuses application-supplied values. A uuid generated outside the database serves the same role when rows are created on many machines with no shared counter.

The safe default for application tables is surrogate primary key plus UNIQUE on the business identifier. The surrogate never changes, so references stay put; the UNIQUE constraint keeps the real-world identifier honest, and a stolen or mis-typed SKU still collides loudly instead of silently creating a second product. Natural keys remain a good primary key choice when the domain truly guarantees them — an ISO country code is assigned by a standards body and changes very rarely (though BU for Burma did become MM, and TP for East Timor became TL) — but treat "this will never change" as a claim to test, not assume.

One warning about display values. The readable reference on an order, ORD-2026-0142, exists for people on the telephone; keep it as a UNIQUE column next to the surrogate key, not as the key itself. If the numbering scheme is ever revised — a new prefix, a different year — only that column changes, and no reference anywhere has to move.

04. Composite keys and junction tables

Some rows are identified by a composite key: more than one column acting together. The most common place you meet one is a many-to-many relationship. Products and collections both say "many", so neither side can hold a single reference column. The fix is a junction table with one row per pairing, foreign keys to both sides, and the pair as its primary key — which also makes the same pairing impossible to record twice.

Attributes of the pairing, such as the position of a product inside a collection, live on the junction row: they are facts about the pair, not about either side alone. Run it in the lab container you met in the first SQL session — under its own name and port, so the two labs can run side by side:

Terminal
docker run --name rdm-lab \
  -e POSTGRES_PASSWORD=rdmlab \
  -e POSTGRES_DB=store \
  -p 55436:5432 \
  -d postgres:17-alpine

docker exec -it rdm-lab psql -U postgres -d store
Expected output (the version line shows the 17.x release your image contains)
psql (17.12)
Type "help" for help.

store=#
SQL · store=#
CREATE TABLE products (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku   text NOT NULL UNIQUE,
  name  text NOT NULL
);

CREATE TABLE collections (
  id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slug text NOT NULL UNIQUE
);

CREATE TABLE collection_products (
  collection_id bigint NOT NULL REFERENCES collections(id),
  product_id    bigint NOT NULL REFERENCES products(id),
  position      integer NOT NULL CHECK (position > 0),
  PRIMARY KEY (collection_id, product_id)
);

INSERT INTO products (sku, name) VALUES
  ('CBL-USBC-1M', 'USB-C cable 1m'),
  ('PAD-STD',     'Desk mat');

INSERT INTO collections (slug) VALUES ('gifts-under-20');

INSERT INTO collection_products (collection_id, product_id, position) VALUES
  (1, 1, 1),
  (1, 2, 2);
Expected output
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 1
INSERT 0 2

Now try to put the desk mat in the same collection twice. The composite primary key rejects the pairing:

SQL · store=#
INSERT INTO collection_products (collection_id, product_id, position) VALUES
  (1, 2, 3);
Expected output
ERROR:  duplicate key value violates unique constraint "collection_products_pkey"
DETAIL:  Key (collection_id, product_id)=(1, 2) already exists.

The pair is unique, not each side: the same product may appear in a second collection, because that is a different pair. Each side on its own is a foreign key, and each pairing carries its own position — the attribute that belonged to the relationship in the ER diagram now has a home.

05. Check your understanding

Practice check · 3 questions

Keys in practice

Reason about key choices in three concrete situations.

Q1. order_lines could be keyed on (order_id, line_no) or on (order_id, product_id). What does the second choice prevent that the first allows?
Q2. orders.customer_id references customers(id). A legacy table must reference customers by email instead. What does customers need for that foreign key to be allowed?
Q3. Which statement about a surrogate key such as an identity column is true?
Practice only: not graded, not saved, not evidence.

06. Apply it

Make the key plan for your clinic model from the previous lesson:

  1. For each entity, list every candidate key and test it for uniqueness, missing values and stability. Flag any candidate whose stability you are assuming rather than know.
  2. Choose a primary key per entity, and say in one line why it is a surrogate or a natural key.
  3. List the business identifiers that stay UNIQUE next to the primary key, such as a patient number or a licence reference.
  4. Find every many-to-many pairing and write the junction table: both foreign keys, the composite primary key, and any attributes of the pairing.

You now have the key plan you will need for the worked example and for the DDL you will write in the practice.

07. Review prompt

Without looking back: list the four properties a key must have. What is the safe default key design for an application table, and what does each half of it protect? When is a natural primary key a defensible choice? And what three things does a junction table always contain?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check