Keys identify rows and link tables. Interviewers love the vocabulary — and the choice between natural and surrogate keys matters in every real schema.
| Key | Definition | In employees |
|---|---|---|
| Super key | Any set of columns that uniquely identifies a row | {emp_id}, {email}, {emp_id, name}, … |
| Candidate key | A minimal super key — remove any column and it is no longer unique | {emp_id}, {email} (if always present) |
| Primary key | The candidate key chosen as the row's identity; unique and not null | emp_id |
| Alternate key | A candidate key not chosen as primary (usually enforced with UNIQUE) | email |
| Foreign key | Column(s) referencing a key of another (or the same) table | dept_id, manager_id |
| Composite key | A key made of two or more columns | order_items (order_id, product_id) |
| Surrogate key | A meaningless generated id (auto-increment, UUID) | emp_id |
| Natural key | A key with business meaning | email, PAN number, ISBN |
Super keys → minimal → Candidate keys → chosen → Primary key → others → Alternate keys
Composite primary key
-- 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;order_id | product_id | quantity
---------+------------+---------
101 | 1 | 1
101 | 2 | 1INSERT INTO order_items VALUES (101, 1, 3, 55000); -- same pair againUNIQUE constraint failed: order_items.order_id, order_items.product_idNatural vs surrogate keys
-- 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?