Skip to content
  • Keys: Super, Candidate, Primary, Foreign · SQL

Keys: Super, Candidate, Primary, Foreign

LearnViaNotes @learnvianotes· 2 min read

Keys identify rows and link tables. Interviewers love the vocabulary — and the choice between natural and surrogate keys matters in every real schema.

KeyDefinitionIn employees
Super keyAny set of columns that uniquely identifies a row{emp_id}, {email}, {emp_id, name}, …
Candidate keyA minimal super key — remove any column and it is no longer unique{emp_id}, {email} (if always present)
Primary keyThe candidate key chosen as the row's identity; unique and not nullemp_id
Alternate keyA candidate key not chosen as primary (usually enforced with UNIQUE)email
Foreign keyColumn(s) referencing a key of another (or the same) tabledept_id, manager_id
Composite keyA key made of two or more columnsorder_items (order_id, product_id)
Surrogate keyA meaningless generated id (auto-increment, UUID)emp_id
Natural keyA key with business meaningemail, PAN number, ISBN

Super keys → minimal → Candidate keys → chosen → Primary key → others → Alternate keys

Composite primary key

SQL
-- one row per (order, product): the pair is unique, neither column alone is
SELECT order_id, product_id, quantity FROM order_items WHERE order_id = 101 ORDER BY product_id;
Output
order_id | product_id | quantity
---------+------------+---------
101      | 1          | 1
101      | 2          | 1
SQL
INSERT INTO order_items VALUES (101, 1, 3, 55000);    -- same pair again
Error
UNIQUE constraint failed: order_items.order_id, order_items.product_id

Natural vs surrogate keys

PostgreSQL
-- UUIDs: globally unique, generated anywhere (useful across services / offline clients)
CREATE TABLE sessions (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id INT NOT NULL);
-- prefer time-ordered UUIDv7 for B-tree friendliness (random v4 keys scatter inserts)

What is the difference between a primary key and a candidate key?

Can a table have no primary key?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report