← Back to SQL, page 9

sql-0179 · Medium mid

What is a composite primary key, and when is it a better choice than a surrogate id?

A composite primary key uses several columns together, such as (student_id, course_id) in an enrolment table. It fits junction tables and other rows whose identity is the combination, because it prevents duplicates directly. A surrogate id is simpler for rows referenced by many other tables, but then the natural combination still needs a UNIQUE constraint.

Full answer
sql
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol VALUES (1, 10), (1, 20), (2, 10);
SELECT * FROM enrol ORDER BY student_id, course_id;
student_idcourse_id
110
120
210

The second enrolment of student 1 in course 10 is rejected:

sql
CREATE TABLE enrol2 (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol2 VALUES (1, 10), (1, 10);
-- error on purpose
text
Error: UNIQUE constraint failed: enrol2.student_id, enrol2.course_id

With a surrogate id instead, the duplicate would be accepted unless a separate UNIQUE (student_id, course_id) existed. Forgetting that constraint is a common source of duplicate rows.

Column order matters for the index behind the key: (student_id, course_id) supports lookups by student alone, but not by course alone, so add an index on course_id if that query is common.

Composite keys get awkward when other tables must reference the row, because every referencing table then needs all the columns.

sql
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol VALUES (1, 10), (1, 20), (2, 10);
SELECT * FROM enrol ORDER BY student_id, course_id;

-- error on purpose
CREATE TABLE enrol2 (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id));
INSERT INTO enrol2 VALUES (1, 10), (1, 10);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Composite keys combine columns into one identity
  • Ideal for junction tables
  • Surrogate ids still need a UNIQUE on the natural key
  • Column order affects which lookups the index serves

Common mistakes

  • Adding a surrogate id to a junction table and forgetting the UNIQUE
  • Ignoring index order for lookups by the second column

Follow-ups

  • How would a grade-history table reference an enrolment?
  • When would you add a surrogate id to a junction table?

Tips

  • Mention the index order point