SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 2 / 37

Junior

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.

implemented byimplemented bypoints toPrimary keyone, not NULLUnique indexUnique keymany, NULL allowedChild foreign key

3 points to say:

  1. PK: one, not NULL, identifies the row, target of FKs; unique: many, NULL allowed, blocks duplicate business keys.
  2. Unique allows multiple NULLs (PostgreSQL 15+ has NULLS NOT DISTINCT); a key is a constraint, an index is a structure.
  3. 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.