A composite key in a database is a primary key that consists of two or more columns in a table. Instead of using a single column to uniquely identify a record, the combination of multiple columns together ensures uniqueness.
Key Points:
- Purpose: Ensures that each row in a table is unique when a single column is not sufficient.
- Composition: Made up of two or more attributes (columns).
- Uniqueness: The combination of all columns in the composite key must be unique for every row. Individually, the columns may contain duplicate values.
- Use case: Common in many-to-many relationship tables (junction tables).
Example:
Consider a table CourseEnrollment:
| student_id | course_id | enrollment_date |
|---|---|---|
| 1 | 101 | 2025-08-01 |
| 1 | 102 | 2025-08-02 |
| 2 | 101 | 2025-08-01 |
- Here, neither
student_idnorcourse_idalone can uniquely identify a row, because a student can enroll in multiple courses and a course can have multiple students. - Composite key:
(student_id, course_id)ensures each row is unique.
So, a composite key is all about uniqueness through combination, not a single column.
