Part 09 / Topic 3 of 7
Cardinality
Three shapes cover every relationship, and each has one standard implementation:
One-to-many — the workhorse. One customer, many orders: the many side carries a foreign key (orders.customer_id). You have joined across these for four parts.
One-to-one — rare, deliberate. A customer and their tax profile: same key on both tables, with the dependent table's primary key also a foreign key. Used to split off huge/secret/optional columns; most of the time it's a sign the columns just belong on the main table.
Many-to-many — products and tags, students and courses. No foreign key placement works: a product has many tags and a tag has many products. The answer is always a junction table holding both keys:
CREATE TABLE tags (
tag_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE product_tags (
product_id integer REFERENCES products(product_id) ON DELETE CASCADE,
tag_id integer REFERENCES tags(tag_id) ON DELETE CASCADE,
PRIMARY KEY (product_id, tag_id)
);
INSERT INTO tags (name) VALUES ('bestseller'), ('gift');
INSERT INTO product_tags VALUES (1, 1), (5, 1), (5, 2), (7, 2);
SELECT t.name AS tag, string_agg(p.name, ', ' ORDER BY p.name) AS products
FROM product_tags AS pt
JOIN tags AS t ON t.tag_id = pt.tag_id
JOIN products AS p ON p.product_id = pt.product_id
GROUP BY t.name
ORDER BY t.name;
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 4
tag | products
------------+----------------------------------
bestseller | Laptop Pro 14, SQL for Beginners
gift | Chef Knife, SQL for Beginners
(2 rows)
The composite primary key (product_id, tag_id) says "each pairing once" — the junction is the relationship. And when the relationship carries facts of its own, they live here: shopdb's order_items is exactly a junction between orders and products that grew quantity and unit_price.
🧪 Quick quiz — answer from memory, then check.
- Where does the foreign key live in a one-to-many?
- How do you model many-to-many — and where does
quantitygo for orders/products?
Show the answers
- On the many side (each order points at its one customer).
- A junction table with both foreign keys and a composite primary key; relationship data like quantity lives on the junction — that's what order_items is.
Done here? The practice set for Part 9 — 4 exercises with solutions — is on the part page.