Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 42/ 160
03. Joins & Relational Querying

Bridge / Junction Tables for Many-to-Many Relationships

Resolve M:N links with junction tables and composite keys.

BeginnerJunction Table · Composite Keys3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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).

Tagging productsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE product_tags (2  product_id bigint NOT NULL REFERENCES products (id) ON DELETE CASCADE,3  tag_id bigint NOT NULL REFERENCES tags (id) ON DELETE CASCADE,4  PRIMARY KEY (product_id, tag_id)5);67CREATE INDEX product_tags_tag_idx ON product_tags (tag_id, product_id);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE TABLE CREATE INDEX

Note: Representative PostgreSQL statuses; the referenced tables must already exist.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Products with every requested tagQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  p.id,3  p.name4FROM5  products p6  JOIN product_tags pt ON pt.product_id = p.id7WHERE8  pt.tag_id IN (3, 7)9GROUP BY10  p.id,11  p.name12HAVING13  COUNT(*) = 2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
idname
18Canvas Backpack
27Travel Organizer

Note: Illustrative products 18 and 27 are the ones linked to both tag IDs 3 and 7.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Join through the bridge for lists; GROUP BY + HAVING COUNT for "has all of".

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Modelling

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.

Focus at this step

students ⇄ courses

What to watch at this step
Foreign keys
neither side can hold one
Tip: use ← → to move between steps

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

Junction table
Best for: Almost every many-to-many relationship

Strengths: Enforced with foreign keys; indexable in both directions; holds link attributes.

Watch out: One extra join each way.

Array or JSON column of ids
Best for: Small, read-only tag lists in PostgreSQL

Strengths: No extra table; one row read.

Watch out: No foreign keys; harder to query from the other side; updates rewrite the row.

Comma-separated text
Best for: Nothing in a relational database

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?
Interview tip: Draw the three tables, say the composite key out loud, then mention the reverse index and a link attribute like role. That covers the details interviewers check for.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Understanding Relationships (One-to-One, One-to-Many, Many-to-Many)
Next topic
INNER JOIN Mechanics & Multi-Table Joins