Explain the concept of a 'Composite Key'.

Instruction: Define a 'Composite Key' and provide an example scenario where it's used.

Context: This question tests the candidate's knowledge of database key concepts, specifically focusing on 'Composite Keys' and their application.

Updated

Official answer

A composite key uses two or more columns together to identify a row. If it is a candidate key, the combination is unique and minimal: no proper subset already identifies every row.

For PostgreSQL:

CREATE TABLE enrollment (
  student_id integer NOT NULL,
  course_id integer NOT NULL,
  enrolled_on date NOT NULL,
  PRIMARY KEY (student_id, course_id)
);

A student can take several courses, and a course can have several students, but a student–course pair appears once. That schema assumes repeated enrollments in the same course are not separate records; if they are, the key must reflect the actual grain.

A foreign key to this primary key must reference the full combination with compatible columns. The resulting index can support some access patterns, but column order and predicates matter; the key alone does not guarantee faster queries or enforce authorization. A surrogate ID may be useful while retaining a UNIQUE constraint for the required business combination.

Related Questions