How does a primary key differ from a unique key, and a key from an index?
Short answer
A primary key identifies each row: exactly one per table, never NULL. A unique key also blocks duplicates, but a table can have many, and the columns may be NULL. A key is a rule about data; an index is a structure for fast lookup.
3 points to say:
- PK: one, not NULL, identifies the row, target of FKs; unique: many, NULL allowed, blocks duplicate business keys.
- Unique allows multiple NULLs (PostgreSQL 15+ has
NULLS NOT DISTINCT); a key is a constraint, an index is a structure. - Use a surrogate PK + unique on the natural key; in PostgreSQL an FK gets no index automatically.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.