Bridge Tables
in SQL
Master the essential technique for modeling many-to-many relationships in relational databases using bridge (junction) tables.
What is a Relationship in a Database?
In relational databases, a relationship describes how rows in one table connect to rows in another table. These connections are established using primary keys and foreign keys.
The Many-to-Many Problem
Consider Students and Courses: one student can enroll in many courses, and one course can have many students. You cannot represent this with a single foreign key in either table.
Enter the Bridge Table
A bridge table (also called a junction table, join table, or associative table) is a third table that sits between the two original tables and converts a many-to-many relationship into two one-to-many relationships.
The Core Rule of Bridge Tables
Anatomy of a Bridge Table
Bridge Table vs. Regular Table
| Bridge Table | Regular Entity Table | |
|---|---|---|
| Primary Purpose | Link two entities together | Store data about one entity |
| Primary Key | Composite (two FKs) | Single column (often auto-increment) |
| Foreign Keys | Always has at least 2 | May have 0 or more |
| Own Data | Optional (attributes of the link) | Core entity attributes |
| Naming | Combines both entity names | Singular noun (e.g., Student) |
How to Create a Bridge Table
Example 1: Creating the Tables
Example 2: Querying Through a Bridge
Goal: Find all courses that student "Alice" is enrolled in.
Example 3: Authors and Books
A book can have multiple authors, and an author can write multiple books. This is a classic many-to-many scenario.
Real-World Bridge Tables Everywhere
Optional Attributes on the Bridge
Bridge tables often carry extra columns that describe the relationship itself, not the entities. These attributes only make sense in the context of both entities together.
| Bridge Table | FK Columns | Relationship Attributes |
|---|---|---|
| enrollments | student_id, course_id | grade, enrollment_date |
| order_items | order_id, product_id | quantity, unit_price |
| cast_members | actor_id, movie_id | role_name, billing_order |
| playlist_songs | playlist_id, song_id | position, added_date |
Composite PK vs. Surrogate Key
Some developers add a separate auto-increment ID to the bridge table instead of using a composite primary key. Both approaches work.
Common Mistakes to Avoid
Question 1 of 5
What is the primary purpose of a bridge table in a relational database?
Question 2 of 5
Which of the following is the minimum set of columns a bridge table must contain?
Question 3 of 5
Given tables actors and movies, a bridge table cast_members has columns (actor_id, movie_id, role_name). What serves as the composite primary key?
Question 4 of 5
A developer stores course IDs as a comma-separated string in the students table: "101,102,103". Why is this a problem?
Question 5 of 5
To find all students enrolled in "Biology", how many JOIN operations are needed when using a bridge table?