Sub topic 11
Many-to-many relationships with junction tables
This chapter assumes you can write CREATE TABLE, declare a primary key and a foreign key, and read the ON DELETE actions covered earlier. Examples use PostgreSQL syntax.
Why a foreign key alone is not enough
A one-to-many relationship needs one foreign key on the "many" side. An order belongs to one customer, so orders.customer_id is enough.
A many-to-many relationship is different. One order can contain many products, and one product can appear in many orders. You cannot put product_id in orders, because an order would be limited to one product. You cannot put order_id in products, because a product would be limited to one order. Storing a list of ids in one column breaks the rule that a column holds a single value, and the database cannot check the ids against the parent table.
The standard solution is a third table, called a junction table (also called a bridge, link, or association table). It holds one row for each pairing of the two entities. Each row has two foreign keys, one to each parent. This turns one many-to-many relationship into two one-to-many relationships.
Building the junction table
The orders and customers tables come from the earlier chapters. The products and order_items tables are new.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id) ON DELETE RESTRICT
);Four design decisions are worth reading carefully.
- Both foreign key columns are
NOT NULL. A row that links an order to nothing has no meaning. Primary key columns are alreadyNOT NULL, and the explicit declaration makes the intent clear. - The composite primary key is
(order_id, product_id). It guarantees each product appears at most once per order. Adding the same product twice is rejected, and the application must updatequantityinstead. - The relationship has its own column,
quantity. Data that describes the pairing, rather than either parent, belongs in the junction table. Other examples areenrolled_onin a student-course table orrolein a project-member table. - The two foreign keys use different actions.
ON DELETE CASCADEonorder_idmeans that deleting an order removes its line items, since they cannot exist without it.ON DELETE RESTRICTonproduct_idblocks deleting a product that appears in any order, which protects order history.
Composite key or surrogate key?
The composite key is not the only option. Some teams add a generated order_item_id and make that the primary key. Compare the two approaches.
| Aspect | Composite key `(order_id, product_id)` | Surrogate `order_item_id` |
|---|---|---|
| Prevents duplicate pairs | Yes, automatically | Only with an extra `UNIQUE (order_id, product_id)` |
| Extra column and index | No | Yes |
| Referencing a single row from another table | Needs two columns | Needs one column |
| Works well with some ORMs | Sometimes awkward | Usually simpler |
If you choose the surrogate key, keep the UNIQUE (order_id, product_id) constraint. Without it, the table silently allows duplicate pairs, which is a common mistake.
Use the composite key when the table is purely a link and nothing else references its rows. Consider the surrogate when other tables need to point at individual rows, or when the same pair may legitimately repeat. For example, a person might hold the same role on a project in two separate time periods.
Working with the junction table
Inserts must satisfy both foreign keys. The parent rows have to exist first.
INSERT INTO products (name) VALUES ('Keyboard'), ('Mouse');
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1, 1, 2),
(1, 2, 1);
-- Fails: the pair (1, 1) already exists
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1, 1, 5);If you want "add or increase" behavior, PostgreSQL provides ON CONFLICT on the primary key.
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1, 1, 5)
ON CONFLICT (order_id, product_id)
DO UPDATE SET quantity = order_items.quantity + EXCLUDED.quantity;Querying across the junction table
To go from orders to products, join through the junction table. This needs two joins, one for each foreign key.
SELECT o.order_id, p.name, oi.quantity
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
ORDER BY o.order_id, p.name;To find products that were never ordered, use a LEFT JOIN and test for the missing side.
SELECT p.product_id, p.name
FROM products AS p
LEFT JOIN order_items AS oi ON oi.product_id = p.product_id
WHERE oi.product_id IS NULL;Indexing the junction table
The composite primary key creates an index on (order_id, product_id). That index serves lookups by order_id alone, because order_id is its leading column. It does not efficiently serve lookups by product_id alone, such as "which orders contain this product?" It also affects the ON DELETE RESTRICT check, which must find matching rows in order_items when you delete a product. Add an index for the second direction.
CREATE INDEX idx_order_items_product_id ON order_items (product_id);The right index depends on which direction your queries and deletes use most. Alternatively, define the primary key as (product_id, order_id) if lookups by product dominate.
Common mistakes
- Missing primary key or unique constraint. The table accepts duplicate pairs, and totals become wrong.
- Cascading in both directions without thought.
CASCADEon the product foreign key would delete order lines when a product is removed, which erases sales history. - Putting attributes in the wrong table. The price a customer paid belongs in
order_items, not only inproducts, because the product's price can change later. - No index for the second foreign key. Deletes from the parent table then scan the whole junction table.
Exercise
A students table and a courses table need a many-to-many relationship, and you also want to store the grade each student received in each course. Write the junction table, ensure a student cannot enroll in the same course twice, and decide what should happen to enrollments when a student is deleted and when a course is deleted. Assume both parent tables use student_id and course_id as integer primary keys.
Show answer
CREATE TABLE enrollments ( studentid INTEGER NOT NULL, courseid INTEGER NOT NULL, grade CHAR(1), PRIMARY KEY (studentid, courseid), FOREIGN KEY (studentid) REFERENCES students (studentid) ON DELETE CASCADE, FOREIGN KEY (courseid) REFERENCES courses (courseid) ON DELETE RESTRICT ); The composite primary key stops duplicate enrollments. Deleting a student removes that student's enrollments, because they have no meaning alone. Deleting a course is blocked while enrollments exist, which protects grade records. The grade column is nullable because it is unknown until the course ends. An index on course_id helps lookups by course.