How do you design a schema to properly handle a many to many relationship between two entities, such as students and courses?
Short answer
You create a separate junction table, sometimes called a bridge or associative table, that contains foreign keys referencing both related tables, letting a single student be linked to many courses and a single course be linked to many students, without needing to duplicate data…
Advertisement
AModel answer
You create a separate junction table, sometimes called a bridge or associative table, that contains foreign keys referencing both related tables, letting a single student be linked to many courses and a single course be linked to many students, without needing to duplicate data in either the students or courses tables themselves.
CREATE TABLE StudentCourses (
StudentId INT,
CourseId INT,
PRIMARY KEY (StudentId, CourseId),
FOREIGN KEY (StudentId) REFERENCES Students(StudentId),
FOREIGN KEY (CourseId) REFERENCES Courses(CourseId)
);Real-world example
A university's course registration system uses a junction table to track which students are enrolled in which courses, correctly supporting the reality that each student can take many courses and each course can have many students.
Likely follow-ups
- What additional columns might a junction table need beyond the two foreign keys?
- How do you query a junction table to find all courses a specific student is enrolled in?
Related topics