Composite Keys

Difficulty: Beginner

Question

What is a composite primary key? When would you use one instead of a single surrogate ID column?

Answer

A composite primary key is a primary key made of two or more columns whose combination must be unique and non-null, even though each column on its own can repeat. A classic example is enrollments(student_id, course_id): a student takes many courses and a course has many students, but the same pair should appear only once. Composite keys are most natural in junction (many-to-many) tables and in child tables whose rows are identified relative to a parent.

Where composite keys fit well

  • Junction tables: user_roles(user_id, role_id), product_tags(product_id, tag_id). The pair is the identity and the key doubles as the duplicate guard.
  • Dependent child rows: order_items(order_id, line_no), where a line number only makes sense within one order.
  • Time-series or partitioned data: (device_id, recorded_at), which also clusters a device's readings together in engines like InnoDB.
  • Sharded tables: tools like Citus require the distribution column to be part of the primary key, so (merchant_id, order_id) is common.

Column order matters

A composite key creates a composite index, and indexes are sorted by the first column, then the second. That means:

  • WHERE student_id = 7 uses the key efficiently (leftmost prefix).
  • WHERE course_id = 42 alone cannot use it efficiently. Add a separate index on (course_id) or (course_id, student_id) if you query that direction.

Put the column you filter by most often, or with equality, first.

Composite key vs surrogate ID

AspectComposite natural keySurrogate id + unique constraint
Duplicate preventionBuilt inNeed a separate UNIQUE(a, b)
Foreign keys pointing hereChild must carry all key columnsOne column
ORM friendlinessSome ORMs need extra configWorks everywhere
StorageNo extra columnExtra column and index
Changing a key columnPainful, cascades to childrenEasy, ID stays stable

A common, pragmatic pattern is a surrogate id as the primary key plus a UNIQUE (student_id, course_id) constraint. You keep simple references and still block duplicates. For pure junction tables with no children, a composite primary key alone is clean and efficient.

Mistakes to avoid

  • Forgetting the uniqueness rule entirely and allowing a user to be assigned the same role twice.
  • Including a mutable column (like an email) in the key.
  • Making the key so wide that every secondary index (which in InnoDB stores the PK) becomes bloated.

Code examples

Junction table with a composite primary key

CREATE TABLE enrollments (
  student_id  BIGINT NOT NULL REFERENCES students(id),
  course_id   BIGINT NOT NULL REFERENCES courses(id),
  enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (student_id, course_id)        -- pair must be unique
);

-- Reverse lookups need their own index
CREATE INDEX idx_enrollments_course ON enrollments (course_id);

INSERT INTO enrollments (student_id, course_id) VALUES (7, 42);
INSERT INTO enrollments (student_id, course_id) VALUES (7, 42);
-- ERROR: duplicate key value violates unique constraint "enrollments_pkey"

-- Alternative: surrogate key plus uniqueness
-- id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
-- UNIQUE (student_id, course_id)

The composite key both identifies the row and prevents duplicate enrollments. The extra index supports "which students are in course 42" queries.

Key points

  • A composite key is unique as a combination; individual columns can repeat.
  • Most common in junction tables and dependent child tables.
  • Column order determines which queries the key index can serve (leftmost prefix).
  • Surrogate id plus a UNIQUE constraint is a popular alternative.
  • Child tables referencing a composite key must carry every key column.

Common follow-up questions

  • How does column order in a composite index affect query performance?
  • How would a foreign key reference a composite primary key?
  • Would you use a composite key or a surrogate key for an order_items table?
  • What is a candidate key?

Interview tips

  • Use a many-to-many example; it is the clearest justification for a composite key.
  • Mention the leftmost-prefix rule; it connects key design to indexing.
  • Present the surrogate-plus-unique alternative and when you would choose each.

Concepts covered

Composite Key, Primary Key, Junction Table, Column Order, Leftmost Prefix

More Database Design questions