Course contentsShow
← Databases & SQL
Lesson 122 of 1,9532. Querying and Data RetrievalFree lesson

Resolving Many-to-Many Relationships

Query data across bridge tables to connect entities with complex associations.

Understanding Many-to-Many Relationships

In this lesson, you will learn how to connect two entities that share a complex, multi-sided relationship by using a "bridge table."

The Problem: When One Isn't Enough

In database design, a Many-to-Many relationship happens when one record in Table A relates to many records in Table B, and vice versa. For example, consider Students and Classes. One student can enroll in many classes, and one class can hold many students.

If you try to link these directly, you’d end up with messy, duplicated data. To solve this, we introduce a bridge table (sometimes called a junction or associative table). This table acts as a middleman, turning one complex relationship into two simpler one-to-many relationships.

Querying the Bridge

The bridge table typically contains foreign keys pointing to the primary keys of the other two tables. To see the names of all students enrolled in a specific class, you must "bridge" the tables by joining them together.

Imagine a bridge table called Enrollments. You can query the data like this:

SELECT 
    s.student_name, 
    c.class_name
FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id
JOIN Classes c ON e.class_id = c.class_id;

How it Works

  1. The First Join: You link Students to Enrollments using the student_id. This identifies every enrollment record belonging to that student.
  2. The Second Join: You link Enrollments to Classes using the class_id. This pulls in the actual details of the class associated with that specific enrollment.

By chaining these joins, the database traverses the bridge to provide a clear, readable list of connections. Even though the relationship is complex, the SQL remains straightforward: you simply follow the path from the first table, across the bridge, and into the final table. This structure keeps your data organized and prevents the need to store massive lists of IDs inside a single table cell.

Key Takeaway: To resolve a many-to-many relationship, use a bridge table to store the connections and perform a multi-table join to retrieve the associated records.