Sub topic 8
Modeling one-to-many and many-to-many relationships
This chapter assumes you can read basic SQL, know what a primary key and a foreign key are, and have seen CREATE TABLE and JOIN before. Here you will use those pieces to model how real entities relate to each other.
Why relationships need a design decision
Real data is connected. A customer places orders. An order contains products. A relational database stores each kind of thing in its own table, so you have to choose how to represent the connections between rows.
The only tool the relational model gives you for this is the foreign key: a column whose values must match a key in another table. The shape of the relationship decides where that column goes, and whether you need an extra table.
There are three common cardinalities, meaning how many rows on one side can match rows on the other:
| Relationship | Meaning | Typical example | Implementation |
|---|---|---|---|
| One-to-one | One row matches at most one row | User and user profile | Foreign key with a UNIQUE constraint |
| One-to-many | One row matches many rows on the other side | Customer and orders | Foreign key on the "many" side |
| Many-to-many | Rows on both sides match many rows | Orders and products | Junction table with two foreign keys |
This chapter focuses on the last two, which cover most of what you will model.
One-to-many: the foreign key goes on the many side
A customer can place many orders, but each order belongs to exactly one customer. The rule is to put the foreign key on the "many" side, pointing at the "one" side.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);The customer_id column in orders holds one customer's key. Many order rows can hold the same value, which is what makes the relationship one-to-many. A customer row never stores a list of order ids. A single column cannot hold a list without breaking the rule that each cell contains one atomic value.
In the diagram, || means exactly one and o{ means zero or more. A customer with no orders is valid. An order with no customer is not, because customer_id is NOT NULL.
Reading the relationship with a join
To read both sides together, compare the foreign key to the primary key.
SELECT c.name, o.order_id, o.order_date, o.total_amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_date;Each result row is one order with its customer's name repeated. The name is stored once in customers, and the join reproduces it for every matching order.
Optional versus mandatory
Whether the "many" side must have a parent is controlled by nullability.
customer_id INTEGER NOT NULL REFERENCES ...makes the parent mandatory. Every order needs a customer.customer_id INTEGER REFERENCES ...withoutNOT NULLmakes it optional. An order may exist withNULLin that column, meaning no customer is assigned.
Pick the one that matches the business rule. Allowing NULL by accident is a common source of "orphan-like" rows that no join will ever return, because a NULL never equals anything in a join condition.
What happens when the parent is deleted
A foreign key also answers a question you must decide: what should happen to orders if their customer is deleted? The default in most systems is to reject the delete. You can state other behaviors explicitly.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (customer_id) ON DELETE RESTRICT,
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);| Action | Effect when the parent row is deleted |
|---|---|
| `RESTRICT` / `NO ACTION` | The delete fails while child rows exist |
| `CASCADE` | The child rows are deleted too |
| `SET NULL` | The child column becomes `NULL` (the column must allow it) |
CASCADE is convenient but dangerous for business records such as orders, because one delete can silently remove a lot of data. Use it for dependent data that has no meaning alone, and prefer RESTRICT for records you must keep. In SQLite, foreign key enforcement is off by default and must be enabled with PRAGMA foreign_keys = ON; for each connection.
Many-to-many: add a junction table
An order can contain many products, and a product can appear in many orders. Neither table can hold the foreign key alone. If orders held a product_id, each order could contain only one product. If products held an order_id, each product could be sold only once.
The solution is a third table, called a junction table (also called a link, bridge, or associative table). It holds one row per pairing, and each row points at both sides.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);A many-to-many relationship is really two one-to-many relationships joined at the junction table: one order has many order_items, and one product has many order_items.
The composite primary key
The primary key of order_items is the pair (order_id, product_id). A composite key is a key made of more than one column. It is unique as a pair, not per column. Order 100 can appear many times, and product 7 can appear many times, but the combination (100, 7) can appear only once.
This prevents the same product from being listed twice on the same order. If a customer wants more, you update quantity instead of inserting a second row.
Data that belongs to the relationship
The quantity column does not belong to an order or to a product. It describes the pairing. Any attribute that depends on both sides goes in the junction table. Other examples are the unit price at the time of sale, a discount, or the date a student enrolled in a course.
Storing the price in the junction table also protects history. If products held the only price, changing it would rewrite the apparent cost of every past order.
Working with the three tables
Insert in dependency order: parents first, then the junction rows.
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES (100, 1, '2026-01-15', 59.90);
INSERT INTO products (product_id, name)
VALUES (7, 'Notebook'), (8, 'Pen');
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (100, 7, 2), (100, 8, 5);To list what an order contains, join through the junction table. Two joins connect three tables.
SELECT o.order_id, p.name AS product, 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 = 100
ORDER BY p.name;The result for the data above is:
| order_id | product | quantity |
|---|---|---|
| 100 | Notebook | 2 |
| 100 | Pen | 5 |
Choosing a key for the junction table
There are two common designs, and both are valid.
- Composite primary key from the two foreign keys, as shown above. It enforces "each pairing at most once" without extra work.
- A surrogate key such as
order_item_id, plus aUNIQUE (order_id, product_id)constraint if duplicates are not allowed.
Use the surrogate key when other tables need to reference a single junction row, or when the same pairing may legitimately repeat, such as a person attending the same event on several dates. Without a surrogate key, a table that references the junction row would need to carry both columns.
Indexing the relationship columns
A foreign key constraint checks values, but most databases do not automatically create an index on the foreign key column. PostgreSQL and SQL Server leave it to you, while MySQL's InnoDB engine creates one if none exists. Without an index, "find all orders for customer 1" scans the whole orders table.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);The composite primary key on order_items already gives an index that serves lookups by order_id, because it is the leading column. Lookups by product_id alone, such as "which orders include the Pen?", would benefit from a separate index on product_id. The cost is extra storage and slower writes, which is the trade-off covered in the indexes chapter.
Common mistakes
- Storing a list in one column, such as
product_ids = '7,8'. You cannot enforce foreign keys on it, join on it cleanly, or index it well. Use a junction table. - Putting the foreign key on the wrong side of a one-to-many relationship. If the "one" side holds the key, it can point at only one child.
- Forgetting
NOT NULLon a foreign key that should be mandatory. - Leaving the junction table without a uniqueness rule, which lets duplicate pairs accumulate and makes counts and totals wrong.
- Using
ON DELETE CASCADEon records you need to keep for auditing. - Assuming the database indexed your foreign key column.
Summary
A one-to-many relationship is a foreign key on the many side that points at the primary key of the one side. A many-to-many relationship is a junction table that holds two foreign keys, usually combined as a composite primary key, plus any attributes that describe the pairing. Nullability, delete actions, and uniqueness rules turn your business rules into constraints the database enforces. Index the foreign key columns you search by.
Exercise
A school tracks students and courses. A student can enroll in many courses, and a course has many students. The school also needs to record the grade each student earned in each course. Write the CREATE TABLE statement for the table that links them, so that a student cannot be enrolled in the same course twice. Assume tables students(studentid) and courses(courseid) already exist.
Show answer
CREATE TABLE enrollments ( studentid INTEGER NOT NULL REFERENCES students (studentid), courseid INTEGER NOT NULL REFERENCES courses (courseid), grade VARCHAR(2), PRIMARY KEY (studentid, courseid) ); The composite primary key allows each (student, course) pair only once. The grade column describes the pairing, so it belongs in the junction table, and it allows NULL because a grade does not exist until the course is finished.
Exercise
An orders table has customerid INTEGER REFERENCES customers (customerid) with no NOT NULL. An order is inserted with customer_id set to NULL. Does the foreign key reject it? Will the join between customers and orders return that order?
Show answer
The foreign key does not reject it, because a foreign key is only checked when the value is not NULL. The inner join will not return the order, because NULL never equals any customer_id in the ON condition. To make a customer mandatory, declare the column NOT NULL.
Exercise
Which statement is the best fix for a table products that has a column named category_ids containing values like '3,9,12'?
Show answer
Replace the column with a junction table such as productcategories(productid, category_id) that has foreign keys to products and categories and a composite primary key on the two columns. This lets the database enforce valid category ids, prevent duplicates, and join and index the pairs.