Bridge / Junction Tables for Many-to-Many Relationships
Resolve M:N links with junction tables and composite keys.
In plain words
When many things link to many other things, you keep a separate list of every pair.
Think of it like…
A guest list for a set of parties: rather than writing every party on each guest's card and every guest on each party's card, one sheet lists "Asha, Friday party", "Asha, Saturday party", "Ben, Friday party", one line per invitation.
Where you’ve seen it
An online store tags products: product_tags (product_id, tag_id, PRIMARY KEY (product_id, tag_id)) with foreign keys to products and tags. The product page lists tags by product_id; the "shop by tag" page needs a second index on (tag_id, product_id) to find products for a tag without scanning the whole table.
Words you’ll hear
- Junction table
- A table whose rows each link one row of table A to one row of table B.
- Composite primary key
- A key made of both foreign keys, so each pair appears once.
- Association attributes
- Columns describing the link itself, such as enrolled_at or role.
- Relational division
- Finding rows linked to every item in a set, such as students taking all three courses.
Visual diagram
Theory & example queries
Designing the junction table
The table holds two foreign keys, each referencing one side, and a primary key over both: CREATE TABLE enrollments (student_id bigint REFERENCES students(id) ON DELETE CASCADE, course_id bigint REFERENCES courses(id) ON DELETE CASCADE, enrolled_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (student_id, course_id)); The primary key's index serves "courses for a student"; add CREATE INDEX ON enrollments (course_id, student_id) for "students in a course".
Some teams add a surrogate id column instead of the composite key. That's fine as long as you still add a UNIQUE constraint on (student_id, course_id); without it, a double-clicked enrol button creates two identical rows. If the same pair can legitimately repeat (a student retaking a course each term), the term becomes part of the key: (student_id, course_id, term).
CREATE TABLE product_tags ( product_id bigint NOT NULL REFERENCES products (id) ON DELETE CASCADE, tag_id bigint NOT NULL REFERENCES tags (id) ON DELETE CASCADE, PRIMARY KEY (product_id, tag_id));CREATE INDEX product_tags_tag_idx ON product_tags (tag_id, product_id);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative PostgreSQL statuses; the referenced tables must already exist.
Key takeaway: Two foreign keys, a composite key over both, and an index for the other direction.
Querying through the bridge
Listing one side for the other is two joins: SELECT c.title FROM enrollments e JOIN courses c ON c.id = e.course_id WHERE e.student_id = 1; To show each student with a comma-separated list of courses, join both sides and aggregate with STRING_AGG or ARRAY_AGG grouped by student.
"Which students take all of SQL, Python and Statistics?" is relational division: filter the junction rows to those course ids, group by student and keep groups with the full count: SELECT student_id FROM enrollments WHERE course_id IN (10, 11, 12) GROUP BY student_id HAVING COUNT(DISTINCT course_id) = 3; Also remember the junction row is a natural home for facts about the relationship: the grade, the role a user has in a team, or the quantity of a product in a bundle.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT p.id, p.nameFROM products p JOIN product_tags pt ON pt.product_id = p.idWHERE pt.tag_id IN (3, 7)GROUP BY p.id, p.nameHAVING COUNT(*) = 2;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output2 sample rows
| id | name |
|---|---|
| 18 | Canvas Backpack |
| 27 | Travel Organizer |
Note: Illustrative products 18 and 27 are the ones linked to both tag IDs 3 and 7.
Key takeaway: Join through the bridge for lists; GROUP BY + HAVING COUNT for "has all of".
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Spot the many-to-many
Ask the question both ways: can a student take many courses, and can a course have many students? Two yeses mean a junction table.
students ⇄ courses
When to use it & trade-offs
What it is
A junction table (also called a bridge, join or associative table) stores a many-to-many relationship as rows of pairs. Students take many courses and courses have many students, so neither table can hold a single foreign key to the other. Instead, enrollments (student_id, course_id) holds one row per pairing, with a composite primary key on both columns so the same pair can't be stored twice.
Why it matters: Many-to-many links are everywhere: products and tags, users and roles, orders and promotions, actors and films. Getting the junction table right (keys, indexes in both directions, extra columns on the link) decides whether lookups are fast and whether duplicates or orphans creep in. It's one of the first modelling questions in schema-design interviews.
When to reach for it
- Products and tags, users and roles, students and courses
- Relationships that carry their own data (role, quantity, date)
- Any link you need to query from both sides
When to avoid or be careful
- Storing ids as comma-separated strings
- A surrogate id without a UNIQUE constraint on the pair
- Forgetting the reverse index on large junction tables
Ways to store a many-to-many relationship
Strengths: Enforced with foreign keys; indexable in both directions; holds link attributes.
Watch out: One extra join each way.
Strengths: No extra table; one row read.
Watch out: No foreign keys; harder to query from the other side; updates rewrite the row.
Strengths: None worth having.
Watch out: Breaks first normal form; LIKE searches; no integrity.
Interview signals & numbers to know
When this topic comes up
- “A user can belong to many teams”
- “Design tagging for products”
- “Students who took all of these courses”
- Composite primary keys
- Many-to-many in an ER diagram
Benchmarks & rules of thumb
- 2
- foreign keys in a basic junction table
- 2
- indexes for lookups in both directions
- HAVING COUNT = n
- the relational-division check
Common mistakes & follow-ups
Common interview mistakes
- Leaving out the composite key or unique constraint, then finding the same student enrolled in a course twice.
- Only indexing (student_id, course_id) and wondering why "students in this course" scans the table.
- Putting a course's grade on the students table, where it can only hold one value.
Likely interviewer follow-ups
- How would you model users, teams and each user's role in a team?
- Write a query for products that have all of a list of tags.
- Composite primary key or surrogate id for a junction table: which and why?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Bridge / Junction Tables for Many-to-Many Relationships with hands-on SQL practice and interview Q&A.