Sub topic 11
Many-to-Many Relationships with Junction Tables
Assume you know how to create tables, define primary and foreign keys, and use basic SELECT, INSERT, UPDATE, and DELETE statements. This chapter shows how to represent a many-to-many relationship while keeping invalid combinations out of the database.
Why a junction table is needed
A many-to-many relationship exists when:
- One order can contain many products.
- One product can appear in many orders.
A single foreign key cannot represent both directions. Storing product IDs in a comma-separated column also prevents reliable constraints and joins. Instead, create a third table called a junction table. Each row in the junction table represents one relationship between two parent rows.
Defining the tables
The junction table usually contains two foreign keys. Together, they form a composite primary key, which is a primary key made from multiple columns.
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
);The composite key prevents the same product from appearing twice in one order. For example, (12, 4) identifies product 4 in order 12. A different order can still contain product 4.
The quantity column is an attribute of the relationship. It describes how many units of a product belong to a particular order.
| Constraint | Effect |
|---|---|
| `PRIMARY KEY (order_id, product_id)` | Allows each product once per order |
| `NOT NULL` | Requires both sides of the relationship |
| `CHECK (quantity > 0)` | Rejects zero or negative quantities |
| `ON DELETE CASCADE` | Removes items when their order is deleted |
| `ON DELETE RESTRICT` | Prevents deleting a product still in an order |
Querying the relationship
Join through the junction table to list products in an order:
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
WHERE o.order_id = 12;The join follows the key path orders → order_items → products.
Common errors
- Omitting the composite key allows duplicate product rows for one order.
- Using only
product_idas the primary key prevents a product from appearing in multiple orders. - Making a foreign key nullable allows incomplete relationship rows.
- Cascading deletes from products can erase historical order details unexpectedly.
- Changing the key columns without updating dependent foreign keys breaks the relationship.
Exercise
What constraint prevents product 7 from being added twice to order 12?
Show answer
The composite primary key on (order_id, product_id) rejects the duplicate pair (12, 7).