01 / 21

Many-to-Many
Modeling in SQL

Learn how to model complex relationships between database entities using junction tables: the bridge that connects many records to many others.

SQL

What Are Database Relationships?

In a relational database, tables don't exist in isolation. They connect to each other through relationships: logical links that reflect how real-world entities relate. Understanding these links is the foundation of good database design.

One-to-One
One record in Table A maps to exactly one record in Table B.
One-to-Many
One record in Table A maps to many records in Table B.
Many-to-Many
Many records in Table A can map to many records in Table B.

Many-to-Many in the Real World

Many-to-many relationships are everywhere. Think about these scenarios:

Students \(\leftrightarrow\) Courses
A student enrolls in many courses. A course has many students.
Authors \(\leftrightarrow\) Books
An author writes many books. A book can have many authors.

The Problem with Direct Links

Relational databases can't directly represent a many-to-many link between two tables. A foreign key column can only hold one value per row: it naturally creates a one-to-many relationship.

Students Alice Bob Carol Courses Math Art CS Can't store directly!

The Junction Table Solution

The solution is a third table that sits between the two entities. This table is called a junction table (also known as a bridge table, linking table, or associative table). It holds foreign keys pointing to both sides.

Students student_id (PK) name email Enrollments enrollment_id (PK) student_id (FK) course_id (FK) enrolled_date grade Courses course_id (PK) title credits 1 : N N : 1 Many-to-Many = Two One-to-Many relationships

The Core Rule

This decomposes one many-to-many relationship into two one-to-many relationships. Each entity table has a one-to-many relationship with the junction table.

One-to-Many vs Many-to-Many

One-to-Many Many-to-Many
Tables needed 2 3 (includes junction)
FK placement On the "many" side In the junction table
Example Teacher \(\rightarrow\) Classes Students \(\leftrightarrow\) Courses
Direction One-directional ownership Bidirectional participation
Extra data Stored on child row Stored on junction row

How to Build a Junction Table

1
Identify the two entities that participate in the many-to-many relationship (e.g., Students and Courses).
2
Create a new table named after the relationship or the combination of both entities.
3
Add a foreign key column for each entity's primary key.
4
Add a composite unique constraint on both FK columns to prevent duplicate pairings.
5
Add extra columns for relationship-specific data (e.g., grade, enrollment date, role).

Example: Students and Courses

CREATE TABLE students (
  student_id INT PRIMARY KEY,
  name VARCHAR(100)
);

CREATE TABLE courses (
  course_id INT PRIMARY KEY,
  title VARCHAR(100)
);

CREATE TABLE enrollments (
  enrollment_id INT PRIMARY KEY,
  student_id INT REFERENCES students(student_id),
  course_id INT REFERENCES courses(course_id),
  grade CHAR(2),
  UNIQUE(student_id, course_id)
);

How the Data Flows

Students 1 : Alice 2 : Bob Enrollments student=1 course=101 student=1 course=102 student=2 course=101 student=2 course=103 Courses 101 : Math 102 : Art 103 : CS
Alice \(\rightarrow\) Math, Art
Bob \(\rightarrow\) Math, CS

Example: Actors and Movies

An actor appears in many movies. A movie features many actors. The junction table cast_members holds additional data: the role name each actor played.

CREATE TABLE actors (
  actor_id INT PRIMARY KEY,
  name VARCHAR(100)
);

CREATE TABLE movies (
  movie_id INT PRIMARY KEY,
  title VARCHAR(200)
);

CREATE TABLE cast_members (
  actor_id INT REFERENCES actors(actor_id),
  movie_id INT REFERENCES movies(movie_id),
  role_name VARCHAR(100),
  PRIMARY KEY(actor_id, movie_id)
);

Querying a Many-to-Many

To retrieve data across a many-to-many relationship, you JOIN through the junction table. Here's how to list all courses for a specific student:

SELECT s.name, c.title, e.grade
FROM students s
JOIN enrollments e
  ON s.student_id = e.student_id
JOIN courses c
  ON e.course_id = c.course_id
WHERE s.name = 'Alice';

Extra Attributes on the Junction

Junction tables aren't just two foreign keys. They can hold relationship-specific data that belongs to the pairing itself, not to either entity alone.

Enrollments
grade, enrolled_date, status (active/dropped)
Cast Members
role_name, billing_order, screen_time
Order Items
quantity, unit_price, discount

Primary Key Strategies

There are two common ways to define the primary key of a junction table:

Composite PK
Use PRIMARY KEY(fk_a, fk_b). No separate ID column needed. Automatically prevents duplicate pairs. Simpler schema.
Surrogate PK
Add an auto-increment id column as PK. Add a UNIQUE constraint on (fk_a, fk_b). Easier to reference from other tables.

Common Mistakes

✕ Comma-Separated IDs
Storing multiple IDs in one column (e.g., "101,102,103") breaks normalization and makes querying nearly impossible.
✕ Missing Unique Constraint
Without UNIQUE(fk_a, fk_b), duplicate pairings can creep in: the same student enrolled in the same course twice.
✕ No Foreign Keys
Omitting REFERENCES means the database won't enforce that the IDs actually exist in the parent tables. Orphan records result.

Summary: Relationship Types

One-to-One One-to-Many Many-to-Many
Tables 2 2 3
FK location Either table "Many" side Junction table
Example User \(\rightarrow\) Profile Customer \(\rightarrow\) Orders Students \(\leftrightarrow\) Courses
JOINs needed 1 1 2
Extra data On either row On child row On junction row

Question 1 of 5

A school database needs to track which students participate in which clubs. A student can join many clubs, and a club has many members. What is the correct way to model this?

Question 2 of 5

In a many-to-many model between Authors and Books, where does the junction table's foreign keys point?

Question 3 of 5

You have a junction table called order_items linking Orders and Products. Which piece of data belongs in the junction table rather than the Products table?

Question 4 of 5

To query all movies a specific actor has appeared in, how many JOIN operations are needed?

Question 5 of 5

What is the main purpose of a UNIQUE constraint on both foreign key columns in a junction table?