Relationships
You are on the Facebook team building People You May Know. Mira has 300 friends, and each of them has hundreds more. A friend_id column on her user row holds one friend, so 299 would have nowhere to go. A friendships table holds a row per friend, so all 300 fit, and the friends of her friends are that table joined to itself. The relationship's shape decides the design.
A relationship is a sentence
| user_id | handle |
|---|---|
| 101 | mira |
| 102 | dev |
| 103 | tess |
| post_id | author_id | body |
|---|---|---|
| 9001 | 101 | Launch day |
| 9002 | 101 | Day 2 numbers |
| 9003 | 103 | Hello |
Read row 9002 of posts. Its author_id is 101, and 101 is the primary key of mira's row in users. That matching value is the entire relationship. Delete the author_id column and the 2 tables still hold every user and every post, but no query could say who wrote what.
Where the connection is stored
The foreign key goes on the table whose rows each point at one row of the other table. A post has one author, so one column on posts can hold it. A user has any number of posts, and one column on users can hold only one value per row. Put the column on the wrong table and the model can record a single post per user.
| handle | post_id | body |
|---|---|---|
| mira | 9001 | Launch day |
| mira | 9002 | Day 2 numbers |
| tess | 9003 | Hello |
What the schema cannot say
Many analytical stores accept a foreign key declaration without enforcing it, and some tables carry no declaration at all. The relationship still exists as a promise: every author_id value matches a user_id value. Every join along it relies on that promise, so a team that models a relationship also owns checking it.
- ▸How many rows on each side can connect to one row on the other?
- ▸Must the connection exist, or can a row stand without it?
- ▸Does it point at one other table, at its own table, or at several?
A logistics team has parcels (parcel_id, weight_kg) and warehouses (warehouse_id, city). Each parcel ships from one warehouse, and a warehouse ships thousands of parcels. Which change lets a query report the warehouse behind each parcel?
| Shape | Written | In the app | Where the key lives |
|---|---|---|---|
| One-to-one | 1:1 | A user has one settings row | A foreign key that is also unique |
| One-to-many | 1:N | A user writes many posts | A foreign key on the many side |
| Many-to-many | M:N | Users join many clubs, clubs hold many users | A separate table holding 2 foreign keys |
One-to-many: the default shape
Most relationships in a schema are one-to-many, and the first section already built one. The rule from there now has a name: the foreign key lives on the many side. posts is the many side, so posts carries author_id.
One-to-one: a key that is also unique
The app stores each user's preferences in user_settings. A user has one settings row, and a settings row belongs to one user. The table's primary key is user_id, which is also a foreign key to users. Being the primary key makes it unique, and uniqueness is what caps the relationship at one.
Many-to-many: the relationship gets a table
Users join clubs. One user can be in many clubs, and one club holds many users. Try the foreign key on either side: club_id on users allows one club per user, and user_id on clubs allows one user per club. Neither table can carry it, so the relationship moves into a table of its own, called a junction table.
| user_id | club_id | role | joined_on |
|---|---|---|---|
| 101 | 7 | admin | 2026-03-02 |
| 102 | 7 | member | 2026-03-09 |
| 101 | 8 | member | 2026-04-17 |
| 103 | 8 | member | 2026-04-20 |
One row of memberships means one user belongs to one club. Its primary key is the composite (user_id, club_id), so the same membership cannot be recorded twice. Read the table from the left and it lists the clubs of each user. Read it from the right and it lists the users of each club. A many-to-many relationship is 2 one-to-many relationships meeting in the middle.
The junction table is also the home for facts about the connection itself. role and joined_on describe mira in club 7. They belong to neither mira alone nor club 7 alone: mira is an admin in one club and a member in another.
Fan-out: joining 2 many sides at once
User 101, mira, wrote 2 posts and holds 2 memberships. How many rows does this query return?
NOT NULL carries the decision
| post_id | author_id | club_id | body |
|---|---|---|---|
| 9001 | 101 | 7 | Launch day |
| 9002 | 101 | NULL | Day 2 numbers |
| 9003 | 103 | 8 | Hello |
author_id rejects NULL, so a post with no author can't be written at all. club_id accepts NULL, and post 9002 uses it: mira posted it to her own page. NULL here is a real answer, meaning this post has no club.
Optional changes what a join returns
An inner join keeps only rows that find a match, and NULL matches nothing. Join posts to clubs with an inner join and post 9002 disappears: the table holds 3 posts and the result shows 2. A report built on that join undercounts posts, and nothing in the output says so. A left join keeps every post and fills the club columns with NULL where there is no club.
| post_id | body | club_name |
|---|---|---|
| 9001 | Launch day | Founders |
| 9002 | Day 2 numbers | NULL |
| 9003 | Hello | Runners |
The other end has a minimum too
Turn the sentence around. Must every user have at least one post? No: dev has none, and that is fine. Must every club have at least one member? The business may say yes. No column can hold that rule, because the key lives in memberships and a club row is written before any membership row points at it.
| Minimum | Maximum | Read as | Example |
|---|---|---|---|
| 0 | 1 | zero or one | A post may sit in one club |
| 1 | 1 | exactly one | A post has one author |
| 0 | many | zero or more | A user may write any number of posts |
| 1 | many | one or more | A club needs at least one member |
Deciding: can the row stand alone?
- Deleting the parent must be blocked, or must delete the child rows too
- Inner and left joins agree only if every key is enforced or checked to match a parent
- Deleting the parent can set the key to NULL and keep the child
- Inner joins drop the unmatched rows, left joins keep them
author_id 0, which joins to nothing or to a made-up row.A ride app writes a trips row the moment a rider requests a ride. A driver accepts later, and 12% of requests are cancelled before any driver does. Analysts report that cancellation rate every week. How should trips.driver_id be modeled?
The app's comments table holds the thread under post 9001.
| comment_id | author_id | parent_comment_id | body |
|---|---|---|---|
| 501 | 102 | NULL | Congrats! |
| 502 | 101 | 501 | Thanks dev |
| 503 | 103 | 502 | Well earned |
| 504 | 103 | NULL | What comes next? |
| 505 | 102 | 501 | Party when? |
parent_comment_id holds the comment_id of the comment being replied to. Row 502 replies to 501, and 503 replies to 502. Everything from the earlier sections still applies. The shape is one-to-many: a comment has many replies and at most one parent. The relationship is optional: 501 and 504 start threads, so their parent is NULL.
A hierarchy's self-reference should be optional. Under NOT NULL, a thread starter must still point somewhere: at itself, or at an invented placeholder row. Both corrupt the hierarchy: a walk starting from parent_comment_id IS NULL finds no roots, and a self-pointing row looks like a loop. NULL marks where a thread starts and claims nothing else.
Joining a table to itself
To show each comment beside the comment it answers, the table joins to itself. It appears in the query under 2 aliases, one per role: c is the reply and p is the parent.
Row 502 comes back with the body of 501 beside it, and row 503 with the body of 502. The left join keeps 501 and 504 with a NULL parent_body. Swap in an inner join and both thread starters vanish, which is the optional-relationship rule applied to a table and itself.
One join climbs one level
| Round | Rows added | Why |
|---|---|---|
| 1 | 501, 504 | parent is NULL |
| 2 | 502, 505 | parent is 501 |
| 3 | 503 | parent is 502 |
| 4 | none | no comment replies to 503 |
Where a self-reference breaks
A hierarchy assumes every chain of parents ends at a root. Bad data can break that. If 502's parent were set to 503 while 503's parent stayed 502, the pair would point at each other and no root would lead to them. A walk upward from either one would circle forever. A check for rows where comment_id equals parent_comment_id catches only one-row loops. Longer ones, like this pair, need an upward walk that flags any row reached twice, capped at 50 levels. Loop rows never reach a root, so the walk down from the roots returns fewer rows than the table holds.
One parent column also means one parent per row. Friendship between users breaks that limit: a user has many friends, and each friend has many. That is many-to-many from a table to itself, and it takes a junction table whose 2 foreign keys both point at users.
Friendship runs both ways, so store each as 2 rows, 101 to 102 and 102 to 101, so user_id always means this user and no query checks both columns. Join friendships to itself on f1.friend_id = f2.user_id from mira's rows, drop mira and her current friends, and the rest is the People You May Know candidate list.
The author of comment 501 deletes it. Rows 502 and 505 keep parent_comment_id = 501. Which rows does the recursive query return now?
Polymorphic: one key, several targets
Users like posts, and now they like comments too. One row of likes should mean one user liked one thing, where the thing is a post or a comment. The generic design stores the target's table name as data.
| like_id | user_id | target_type | target_id |
|---|---|---|---|
| 1 | 102 | post | 9001 |
| 2 | 103 | comment | 501 |
| 3 | 101 | comment | 501 |
This table never changes when a new likeable thing appears, which is its appeal. The costs are in what the schema can no longer promise. target_id cannot be declared a foreign key, because it points at 2 tables. A like for comment 777 is accepted even though no such comment exists. target_type is a free string, so Post and post count as different targets. Every join must filter on the type, or a post numbered 501 and comment 501 would both match.
| Design | One row means | Breaks when |
|---|---|---|
| Type and id columns | A like on any target, named by a string | A target is deleted or a type is misspelled |
| One nullable key per target | A like with post_id or comment_id filled | A row fills both keys or neither |
| One table per target | A like on a post, or on a comment, by table | A question spans targets, such as all likes by one user |
The app's `likes` table has `like_id`, `user_id` and a required `post_id`. Product wants more things to be likeable. Change the model as each requirement lands.
| like_idBIGINTPK | user_idBIGINTFK | post_idBIGINTFK |
|---|
| post_idBIGINTPK | author_idBIGINTFK |
|---|
| comment_idBIGINTPK | parent_comment_idBIGINTFK |
|---|
Users can now like comments as well as posts. How does `likes` change?
Circular: 2 tables that point at each other
Users can pin one of their posts to the top of their page, so users gains pinned_post_id. posts already has author_id. Each table now holds a key into the other.
If both keys were required, neither row could be written first: the user needs a post that exists, and the post needs a user that exists. The same deadlock hits a pipeline that loads parents before children, because each table is the other's parent. Break the loop at the optional end. A user exists before any post, so pinned_post_id is nullable: write the user with NULL, write the post, then update the user.
A cleaner break moves the optional relationship into its own table, pinned_posts, keyed by user_id with a post_id beside it. Now users loads first, posts next, pinned_posts last, and no table waits on a later one. Either way the loop hides a rule no key can state: a pinned post must belong to the user who pinned it. This check returns the rows that break it.
> You join a marketplace for handmade furniture. Sellers publish listings, buyers place orders, listings sit in a category tree, and a review can be about a seller or a listing. The orders dashboard shows 8% fewer orders than finance reports, and the nightly load fails whenever a new seller signs up with a default payout account.
order_items is a junction table, and its quantity column belongs to the connection.buyer_id, and a left join brings them back.parent_category_id, and a recursive walk from the roots gives every category its depth.default_payout_account_id nullable and the load order becomes sellers, accounts, then the update.Turn real-world connections into keys: how many, must it exist, and what happens when a table points at itself.
- Category
- Data Modeling
- Difficulty
- intermediate
- Duration
- 18 minutes
- Challenges
- 12 hands-on challenges
Topics covered: What Are Relationships?, Cardinality Explained, Required vs Optional, Self-Referential Tables, Complex Patterns
Lesson Sections
- What Are Relationships?
A schema stores facts about things: a user has a handle, a post has a body. A relationship is a fact that connects 2 things, such as mira wrote post 9001. Tables hold the things. Key values hold the connections between them, and this lesson is about choosing where those values go and what rules they follow. A relationship is a sentence Start with the business, before any table exists. Say the connection out loud as a sentence with 2 nouns and a verb: a user writes posts. The nouns become tables.
- Cardinality Explained
Cardinality is the count in the relationship sentence: how many rows on one side can connect to a single row on the other. Ask it from each side. One user can have many posts, and one post has one author. The pair of answers, one and many, names the shape: one-to-many. There are 3 shapes, and each has its own place for the key. One-to-many: the default shape Cardinality also predicts row counts. Joining from the one side to the many side returns one row per row on the many side, so a user with 2
- Required vs Optional
Cardinality answered how many rows at most. Each end of a relationship also has a minimum, and the minimum is either 0 or 1. A minimum of 1 makes the relationship required: the row cannot exist without its partner. A minimum of 0 makes it optional: the row can stand alone. NOT NULL carries the decision On the side that holds the foreign key, required versus optional is a single choice: may the column be NULL? The app now lets a post go to a club or stay on the author's own page. Every post has a
- Self-Referential Tables
Some relationships connect a table to itself. A comment replies to a comment. An employee reports to an employee. A category sits inside a category. Both ends of the sentence are the same noun, so both ends are rows of the same table, and the foreign key points at its own table's primary key. Joining a table to itself One join climbs one level That join reaches a parent. Reaching a grandparent takes another join, and a thread's depth is unknown in advance. A recursive query handles any depth. It
- Complex Patterns
A plain foreign key points from one table at one other table, in one direction. 2 situations strain that: a row that must point at one of several tables, called a polymorphic relationship, and 2 tables that each point at the other, called a circular relationship. Polymorphic: one key, several targets 2 other designs keep declared foreign keys. Circular: 2 tables that point at each other Both patterns come down to the same move. Find the promise the plain foreign key was making, see which part th