What is Composite Key in SQL explain with example?
Ask by Anubhav Sharma
Updated 31 Aug 2026
Simple example
Suppose you have a
StudentCoursestable:Neither
student_idnorcourse_idis unique by itself:101appears multiple times.10appears multiple times.But the combination
student_id + course_idis unique.So we can define a composite primary key:
Now:
is valid.
But this would fail:
because
(101, 10)already exists.However, this is valid:
because
(101, 20)is a different combination.Why use a composite key?
It's particularly useful for many-to-many relationships.
For example:
A student can take many courses, and a course can have many students. The
StudentCoursestable uses:to ensure that the same student isn't enrolled in the same course twice.
Composite key vs. single-column key
Single-column primary key:
Each
student_idmust be unique.Composite primary key:
The combination must be unique.