Sub topic 10
Modeling one-to-many relationships
This chapter assumes you can write CREATE TABLE statements, know what a primary key and a foreign key constraint are, and can run basic SELECT, INSERT, and DELETE statements. Examples use PostgreSQL syntax.
What one-to-many means
In a one-to-many relationship, one row in a parent table relates to zero, one, or many rows in a child table. Each child row belongs to at most one parent. A customer places many orders, but each order belongs to one customer. A department has many employees, and each employee sits in one department.
This is the most common relationship in relational design. You model it with one rule: the foreign key goes on the "many" side. The child table stores the parent's primary key value in a column, and the database checks that the value exists.
Putting the key on the "one" side does not work. A single column in the parent row can hold only one value, so it could point to only one child. To store many children you would need repeated columns (order1, order2, ...) or a delimited list in one column. Both break the rules of relational design, and the database cannot enforce either.
Declaring the relationship
The parent table needs a primary key, or at least a unique column, for the child to reference. The child declares a column of the same type and a REFERENCES clause.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Three details define the relationship's shape:
- Foreign key on
orders.customer_id. Every order must point to an existing customer. - No unique constraint on
orders.customer_id. Because the column is not unique, many orders can share the same customer. AddingUNIQUEhere would turn the relationship into one-to-one. NOT NULLon the foreign key. This makes the parent mandatory: an order cannot exist without a customer. Without it, an order may have no customer (see the section on optional parents below).
What the database enforces
The foreign key rejects changes that would leave a child row without its parent.
-- Fails: no customer with customer_id 999 exists
INSERT INTO orders (customer_id) VALUES (999);
-- Fails while any order still references customer 1 (default NO ACTION)
DELETE FROM customers WHERE customer_id = 1;The first statement fails because the child points to a missing parent. The second fails because the delete would orphan existing child rows. The same check applies to an UPDATE that changes orders.customer_id to a missing value, or that changes customers.customer_id while orders still use the old value.
Choosing the delete behavior
The default action, NO ACTION, blocks deletes of a parent that still has children. This is a safe starting point. For a one-to-many relationship, choose the action by asking what a child row means without its parent.
| Situation | Suggested action | Reason |
|---|---|---|
| Orders belong to a customer and must be kept for accounting | `NO ACTION` or `RESTRICT` | Deleting a customer with history should be an explicit decision. |
| Order lines exist only as part of an order | `ON DELETE CASCADE` | A line has no meaning without its order. |
| Tickets are assigned to an optional owner | `ON DELETE SET NULL` | The ticket survives and becomes unassigned. |
Here is a cascading child. Deleting an order removes its lines automatically:
CREATE TABLE order_lines (
order_id INTEGER NOT NULL REFERENCES orders (order_id) ON DELETE CASCADE,
line_number INTEGER NOT NULL,
description VARCHAR(200) NOT NULL,
PRIMARY KEY (order_id, line_number)
);The primary key here is composite: the line number is only unique within one order. This is a common pattern for child rows that depend on their parent for identity.
Optional parents
If the relationship is optional, leave out NOT NULL. A NULL foreign key means "no parent", and the database skips the existence check for that row.
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR(200) NOT NULL,
assigned_to INTEGER REFERENCES customers (customer_id) ON DELETE SET NULL
);A common mistake is to store 0 or -1 to mean "none". The foreign key then fails, because no parent has that value. Use NULL. Remember that WHERE assigned_to = NULL never matches. Write WHERE assigned_to IS NULL.
Querying the relationship
To read parent and child together, join on the foreign key matched to the parent's primary key.
SELECT c.name, o.order_id, o.ordered_at
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.ordered_at;An inner JOIN returns only customers that have at least one order. To include customers with no orders, use LEFT JOIN. This pattern also answers "which parents have no children":
SELECT c.customer_id, c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;The WHERE test uses o.order_id, the child's primary key, because it can never be NULL in a real row. A NULL there means the join found no match.
Aggregates count children per parent. Count a child column, not *, or customers with no orders will show a count of 1:
SELECT c.customer_id, c.name, COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;Index the foreign key
PostgreSQL indexes the primary key and unique columns automatically. It does not index the foreign key column on the child. Without an index, a lookup of one customer's orders scans the whole orders table. A parent delete or key update also scans the child table to check for referencing rows.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);MySQL's InnoDB creates this index for you if none exists. Check your database's behavior before relying on it.
Common errors
- Mismatched types. The child column must have a compatible type with the parent key.
INTEGERreferencingBIGINTcan work but invites trouble. Match them exactly. - Referencing a non-key column. The referenced column must be a primary key or have a unique constraint. Otherwise PostgreSQL reports that there is no unique constraint matching the given keys.
- Forgetting
NOT NULL. A mandatory relationship that allowsNULLlets orphan-like rows exist with no parent. - Loading data in the wrong order. Insert parents before children, and delete children before parents, unless a cascade handles it.
- Cascading too widely. Reserve
CASCADEfor owned child rows.
Exercise
A projects table has project_id as its primary key. Each task belongs to exactly one project, and tasks should be deleted when their project is deleted. Write the CREATE TABLE tasks statement, then write a query that lists projects with zero tasks.
Show answer
CREATE TABLE tasks ( taskid INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, projectid INTEGER NOT NULL REFERENCES projects (projectid) ON DELETE CASCADE, title VARCHAR(200) NOT NULL ); SELECT p.projectid FROM projects AS p LEFT JOIN tasks AS t ON t.projectid = p.projectid WHERE t.taskid IS NULL; The foreign key sits on tasks (the many side), is NOT NULL because the project is mandatory, and has no UNIQUE constraint so a project can have many tasks. The LEFT JOIN keeps projects without tasks, and the IS NULL test on the task primary key finds them. You should also add CREATE INDEX ON tasks (projectid).
Exercise
Why does SELECT c.name, COUNT(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id GROUP BY c.name report 1 for customers with no orders, and how do you fix it?
Show answer
With a LEFT JOIN, a customer with no orders still produces one result row, with NULL in all the orders columns. COUNT(*) counts rows, so it returns 1. Use COUNT(o.order_id) instead, which skips NULLs and returns 0.