How to model many to many relationships
· Category: SQL & Databases
Short answer
A many-to-many relationship is modeled with a junction (associative) table that contains foreign keys to both related tables, often with a composite primary key.
Steps
- Create the two main tables:
studentsandcourses. - Create a junction table:
enrollmentswithstudent_idandcourse_id. - Add foreign keys in the junction table referencing both main tables.
- Use a composite primary key on
(student_id, course_id)to prevent duplicates. - Add additional attributes to the junction table if needed, such as enrollment date.
Tips
- Name junction tables with a clear, plural form that describes the relationship.
- Consider surrogate keys if the junction table accumulates many columns or needs independent referencing.
Common issues
- Storing many-to-many data directly in one of the main tables violates normalization and creates update anomalies.
- Missing unique constraints on the junction table allows duplicate relationship rows.r