What is a composite key?

Answer

A composite key (or compound key) is a primary key that consists of two or more columns together. No single column uniquely identifies a row, but the combination of columns is unique. Most common in junction tables (many-to-many relationship tables): CREATE TABLE student_courses ( student_id INT, course_id INT, enrolled_at DATETIME, PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) ); — a student can be in many courses, a course has many students, but each student-course combination is unique. The composite PK prevents the same student from enrolling in the same course twice. Composite index: you can also create a composite index (non-primary-key) on multiple columns for query optimization: CREATE INDEX idx_last_first ON users (last_name, first_name);. Column order matters in composite indexes — the index can be used for queries filtering on last_name alone or last_name + first_name, but NOT first_name alone (leftmost prefix rule).