Database Many-to-Many and Junction Tables
What you will learn
- What a many-to-many relationship is
- Why one foreign key cannot express it
- How a junction table solves it
- How a composite primary key prevents duplicate pairs
- How to add facts about the link itself
1. Both sides have many
A student can take many courses, and a course has many students. This is many-to-many. Other examples: authors and books (a book can have several authors), products and orders, actors and films.
A single foreign key cannot hold it. Put course_id on students and each student gets one course; put a list in a column and you meet the problem from lesson 3.2.
The solution is a third table, a junction table (also called a link, bridge or associative table). Each row records one pair. It breaks many-to-many into two one-to-many relationships:
students 1 ----------< enrolments >---------- 1 courses
2. Building it
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and press Reset data to start again.
The sample databases have junction tables too: in the Shop order_items links orders and products, and in the School enrollments links students and sections. Here we build a new one, themed on the data you chose:
In the Shop, a product can carry several tags (gift, eco, ...) and a tag is on several products.
In the Bank, a customer can switch on several alert types (low balance, large payment, ...) and an alert type is used by several customers.
In the School, a student can join several clubs and a club has several students.
CREATE TABLE tags (tag_id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
CREATE TABLE product_tags (
product_id INTEGER NOT NULL REFERENCES products (product_id),
tag_id INTEGER NOT NULL REFERENCES tags (tag_id),
added_on TEXT NOT NULL,
note TEXT,
PRIMARY KEY (product_id, tag_id)
);
INSERT INTO tags VALUES (1, 'gift'), (2, 'eco');
INSERT INTO product_tags VALUES
(1, 1, '2026-01-10', 'first'),
(1, 2, '2026-01-11', NULL),
(2, 1, '2026-01-12', 'second');
SELECT * FROM product_tags ORDER BY product_id, tag_id;
product_id tag_id added_on note
---------- ------ ---------- ------
1 1 2026-01-10 first
1 2 2026-01-11 NULL
2 1 2026-01-12 second
(3 rows)
CREATE TABLE alert_types (alert_id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
CREATE TABLE customer_alerts (
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
alert_id INTEGER NOT NULL REFERENCES alert_types (alert_id),
added_on TEXT NOT NULL,
note TEXT,
PRIMARY KEY (customer_id, alert_id)
);
INSERT INTO alert_types VALUES (1, 'low balance'), (2, 'large payment');
INSERT INTO customer_alerts VALUES
(1, 1, '2026-01-10', 'first'),
(1, 2, '2026-01-11', NULL),
(2, 1, '2026-01-12', 'second');
SELECT * FROM customer_alerts ORDER BY customer_id, alert_id;
customer_id alert_id added_on note
----------- -------- ---------- ------
1 1 2026-01-10 first
1 2 2026-01-11 NULL
2 1 2026-01-12 second
(3 rows)
CREATE TABLE clubs (club_id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
CREATE TABLE club_signups (
student_id INTEGER NOT NULL REFERENCES students (student_id),
club_id INTEGER NOT NULL REFERENCES clubs (club_id),
added_on TEXT NOT NULL,
note TEXT,
PRIMARY KEY (student_id, club_id)
);
INSERT INTO clubs VALUES (1, 'Chess'), (2, 'Choir');
INSERT INTO club_signups VALUES
(1, 1, '2026-01-10', 'first'),
(1, 2, '2026-01-11', NULL),
(2, 1, '2026-01-12', 'second');
SELECT * FROM club_signups ORDER BY student_id, club_id;
student_id club_id added_on note
---------- ------- ---------- ------
1 1 2026-01-10 first
1 2 2026-01-11 NULL
2 1 2026-01-12 second
(3 rows)
Notice:
- Two foreign keys, one to each side.
- The
PRIMARY KEYover the two id columns is a composite primary key: the pair must be unique. A pair can be recorded only once. added_onandnoteare facts about the link, not about either side alone. That is a main reason to have a junction table.
3. Using it
The junction table is joined to both sides:
SELECT l.name, r.label, j.note
FROM product_tags j
JOIN products l ON l.product_id = j.product_id
JOIN tags r ON r.tag_id = j.tag_id
ORDER BY j.product_id, j.tag_id;
name label note
----------- ----- ------
Steel pan gift first
Steel pan eco NULL
Ceramic mug gift second
(3 rows)
SELECT r.label, COUNT(*) AS links
FROM product_tags j
JOIN tags r ON r.tag_id = j.tag_id
GROUP BY r.tag_id
ORDER BY r.tag_id;
label links
----- -----
gift 2
eco 1
(2 rows)
SELECT l.full_name, r.label, j.note
FROM customer_alerts j
JOIN customers l ON l.customer_id = j.customer_id
JOIN alert_types r ON r.alert_id = j.alert_id
ORDER BY j.customer_id, j.alert_id;
full_name label note
---------- ------------- ------
Chen Park low balance first
Chen Park large payment NULL
Rafi Uddin low balance second
(3 rows)
SELECT r.label, COUNT(*) AS links
FROM customer_alerts j
JOIN alert_types r ON r.alert_id = j.alert_id
GROUP BY r.alert_id
ORDER BY r.alert_id;
label links
------------- -----
low balance 2
large payment 1
(2 rows)
SELECT l.last_name, r.label, j.note
FROM club_signups j
JOIN students l ON l.student_id = j.student_id
JOIN clubs r ON r.club_id = j.club_id
ORDER BY j.student_id, j.club_id;
last_name label note
--------- ----- ------
Khan Chess first
Khan Choir NULL
Haque Chess second
(3 rows)
SELECT r.label, COUNT(*) AS links
FROM club_signups j
JOIN clubs r ON r.club_id = j.club_id
GROUP BY r.club_id
ORDER BY r.club_id;
label links
----- -----
Chess 2
Choir 1
(2 rows)
The second link has no note (NULL). The second query counts the links on each side: the first label has two, the second has one.
4. What it refuses, and who is missing
INSERT INTO product_tags VALUES (1, 1, '2026-02-01', NULL);
IntegrityError: UNIQUE constraint failed: product_tags.product_id, product_tags.tag_id
SELECT l.product_id, l.name
FROM products l
LEFT JOIN product_tags j ON j.product_id = l.product_id
WHERE j.product_id IS NULL
ORDER BY l.product_id
LIMIT 3;
product_id name
---------- ----------------
3 Wooden spoon set
4 Glass jar
5 Chopping board
(3 rows)
INSERT INTO customer_alerts VALUES (1, 1, '2026-02-01', NULL);
IntegrityError: UNIQUE constraint failed: customer_alerts.customer_id, customer_alerts.alert_id
SELECT l.customer_id, l.full_name
FROM customers l
LEFT JOIN customer_alerts j ON j.customer_id = l.customer_id
WHERE j.customer_id IS NULL
ORDER BY l.customer_id
LIMIT 3;
customer_id full_name
----------- -----------
3 Grace Kamau
4 Mei Bianchi
5 Farid Lee
(3 rows)
INSERT INTO club_signups VALUES (1, 1, '2026-02-01', NULL);
IntegrityError: UNIQUE constraint failed: club_signups.student_id, club_signups.club_id
SELECT l.student_id, l.last_name
FROM students l
LEFT JOIN club_signups j ON j.student_id = l.student_id
WHERE j.student_id IS NULL
ORDER BY l.student_id
LIMIT 3;
student_id last_name
---------- ---------
3 Garcia
4 Meyer
5 Torres
(3 rows)
A duplicate pair is refused. The second query uses LEFT JOIN ... IS NULL to find rows of the first table that have no link at all (the first three are shown).
Worked example: model "books and authors"
A book can have several authors, and an author can write several books.
| Step | Decision |
|---|---|
| Entities | books(id, title), authors(id, name) |
| Relationship | many-to-many |
| Junction table | book_authors(book_id, author_id, PRIMARY KEY (book_id, author_id)) |
| Facts about the link | maybe author_order (first author, second author) |
Names are made up.
Common mistakes
- Using a list in a column instead of a junction table.
- Forgetting the composite primary key, so the same pair can be saved twice.
- Putting link facts on one side. A grade belongs in
enrolments, not instudents. - Forgetting a junction table is needed at all when you draw "many" at both ends.
Key takeaways
- Many-to-many needs a third table.
- The junction table has a foreign key to each side.
- A composite primary key on the pair stops duplicates.
- Extra columns describe the link itself.
LEFT JOIN ... IS NULLfinds rows with no links.
Practice
1. Why can't one foreign key express many-to-many?
Show answer
A foreign key holds one value per row, so each row could link to only one row on the other side.
2. What does PRIMARY KEY (student_id, course_id) guarantee?
Show answer
Each student-course pair appears at most once.
3. Where should the grade be stored, and why?
Show answer
In the junction table, because a grade belongs to a student in a course, not to the student or the course alone.
4. Which query found students who have no enrolments?
Show answer
A LEFT JOIN from students to enrolments with WHERE e.student_id IS NULL.
5. Design the tables for "products and orders" (an order has many products, a product is in many orders).
Show answer
products(id, name), orders(id, ordered_on) and a junction table order_items(order_id, product_id, quantity, PRIMARY KEY (order_id, product_id)).
6. Which two one-to-many relationships does a junction table create?
Show answer
One student to many enrolments, and one course to many enrolments.