Sub topic 10
Modeling One-to-Many Relationships
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand rows, columns, and NULL. This chapter uses PostgreSQL-style SQL.
A one-to-many relationship means one row in a parent table can relate to many rows in a child table. For example, one customer can place many orders, but each order belongs to one customer.
The foreign key belongs in the table on the “many” side. The child table stores the primary key of its parent.
Define the parent and child tables
Create the parent table first. Then reference its primary key from the child table.
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
);Here, customers.customer_id identifies each customer. The orders.customer_id column is a foreign key. It must contain a value that already exists in customers.customer_id.
NOT NULL makes the relationship mandatory: every order must have a customer. The database therefore rejects an order that points to no customer.
INSERT INTO customers (email, name)
VALUES ('[email protected]', 'Lee');
INSERT INTO orders (customer_id)
VALUES (1);
-- Fails if customer_id 999 does not exist
INSERT INTO orders (customer_id)
VALUES (999);A primary key can have many matching foreign-key values. That is what allows one customer to have many orders. Each individual order still has only one customer_id value.
| Relationship rule | Column design |
|---|---|
| Every order must have a customer | `orders.customer_id NOT NULL` |
| An order may have no customer | Nullable `orders.customer_id` |
| A customer may have many orders | No `UNIQUE` constraint on `orders.customer_id` |
Query the relationship
Join the tables by matching the foreign key to the parent 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;A common mistake is placing a UNIQUE constraint on orders.customer_id. That would allow only one order per customer, changing the design into a one-to-one relationship.
For large tables, index the foreign key column. PostgreSQL does not automatically create this index when it creates the foreign key.
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);Exercise
Which column should reference customers.customer_id when one customer can have many orders, and should that column be UNIQUE?
Show answer
orders.customerid should reference customers.customerid. It should not be UNIQUE, because several orders may belong to the same customer.