Difficulty: Beginner
What is a composite primary key? When would you use one instead of a single surrogate ID column?
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.
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.order_items(order_id, line_no), where a line number only makes sense within one order.(device_id, recorded_at), which also clusters a device's readings together in engines like InnoDB.(merchant_id, order_id) is common.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.
| Aspect | Composite natural key | Surrogate id + unique constraint |
|---|---|---|
| Duplicate prevention | Built in | Need a separate UNIQUE(a, b) |
| Foreign keys pointing here | Child must carry all key columns | One column |
| ORM friendliness | Some ORMs need extra config | Works everywhere |
| Storage | No extra column | Extra column and index |
| Changing a key column | Painful, cascades to children | Easy, 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.
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.
Composite Key, Primary Key, Junction Table, Column Order, Leftmost Prefix