Module 53: Relationships and ER Diagrams
One-to-many and one-to-one
🏠The everyday picture
A mother can have several children; each child has one mother (one-to-many). Each person has one passport, and each passport belongs to one person (one-to-one).
📘What it really is
- One-to-many is the most common relationship: one customer has many orders; each order has one customer.
- The foreign key goes on the "many" side:
orders.customer_id. -
Never the other way round (a
customers.order_idslist), which can't be enforced or queried properly. -
One-to-one: one row relates to exactly one row in another table, for example
usersanduser_profiles, oremployeesandbank_detailskept separately for security. - The foreign key goes on either side, with a
UNIQUEconstraint so it can't become one-to-many:user_id integer NOT NULL UNIQUE REFERENCES users(id). - Often one-to-one tables can simply be merged; separate them for a reason (security, optional data, very large columns).
- Optional relationships: a nullable foreign key means "may have one": an enquiry's
assigned_tois NULL until someone is assigned.
🖱️Try it
Add an addresses table where a customer can have many addresses (home, office), and a customer_kyc table with
one-to-one sensitive details. Decide which side gets the foreign key in each case, and add the UNIQUE constraint where
needed.
✅Quick check
One customer has many orders. Which table gets the foreign key?
Show the answer
orders, with a customer_id column.
How do you stop a one-to-one relationship becoming one-to-many?
Show the answer
Put a UNIQUE constraint on the foreign key column.
