IntermediateData Modeling · 18 min · 12 challenges

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.

What Are Relationships?

Daily Life
Interviews
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. The verb becomes the relationship. Then say it in the other direction: a post is written by one user. A relationship you can state both ways, with a number in each, is one you can model.
Here is a small social app that the rest of the lesson keeps extending. It has 3 users and 3 posts.
users
user_idhandle
101mira
102dev
103tess
posts
post_idauthor_idbody
9001101Launch day
9002101Day 2 numbers
9003103Hello

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.

users
user_idPKBIGINT
handleVARCHAR
posts
post_idPKBIGINT
author_idFKBIGINT
bodyVARCHAR
A join follows the relationship by matching the 2 columns. This query lists every post with its author's handle.
SELECT
u.handle,
p.post_id,
p.body
FROM posts AS p
JOIN users AS u
ON p.author_id = u.user_id
handlepost_idbody
mira9001Launch day
mira9002Day 2 numbers
tess9003Hello
The result has 3 rows, one per post. The handle mira appears on 2 of them because 2 posts carry her key. The handle dev appears on none: no post row holds 102, so the join finds nothing to match him to. The shape of the output came from the relationship, and the key values alone were enough to predict it.

What the schema cannot say

A schema answers only the questions its relationships store. Suppose product asks which posts each user has shared. No column connects a user to a post they shared, so no query can produce the answer, however clever the SQL. Modeling relationships is deciding, ahead of time, which real-world connections the business will ask about.

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.

3 questions to ask of every relationship
  • ▸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?
Multiple Choice

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?

The rest of the lesson takes those questions in turn. Each one changes where the key column goes, whether it may be empty, or how many tables it takes to hold the connection.

Cardinality Explained

Daily Life
Interviews
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.
ShapeWrittenIn the appWhere the key lives
One-to-one1:1A user has one settings rowA foreign key that is also unique
One-to-many1:NA user writes many postsA foreign key on the many side
Many-to-manyM:NUsers join many clubs, clubs hold many usersA 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.

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 posts appears twice. Count users after that join and mira is counted 2 times. Count posts and the number is right, because a post is what one output row stands for.

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.

users
user_idPKBIGINT
handleVARCHAR
user_settings
user_idPKBIGINT
themeVARCHAR
email_digestBOOLEAN
Remove the uniqueness and nothing stops a second settings row for user 101. The relationship is now one-to-many without any error to say so, and a join that used to return one row per user now returns 2 for mira. A one-to-one pair could always be merged into a single table. Teams split them when the extra columns are wide, rarely read, or filled in by a different system.

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.

users
user_idPKBIGINT
handleVARCHAR
memberships
user_idPKBIGINT
club_idPKBIGINT
roleVARCHAR
joined_onDATE
clubs
club_idPKBIGINT
nameVARCHAR
user_idclub_idrolejoined_on
1017admin2026-03-02
1027member2026-03-09
1018member2026-04-17
1038member2026-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.

Club 7 is Founders and club 8 is Runners, with 2 members each. Counting members per club is a join through the junction table.
SELECT
c.name,
COUNT(m.user_id) AS member_count
FROM clubs AS c
JOIN memberships AS m
ON m.club_id = c.club_id
GROUP BY c.name

Fan-out: joining 2 many sides at once

Fan-out happens when one query joins a table to 2 different many sides. Every row from one many side pairs with every row from the other that shares the key, and the counts multiply.
Multiple Choice

User 101, mira, wrote 2 posts and holds 2 memberships. How many rows does this query return?

SELECT
u.handle,
p.post_id,
m.club_id
FROM users AS u
JOIN posts AS p
ON p.author_id = u.user_id
JOIN memberships AS m
ON m.user_id = u.user_id
WHERE u.handle = 'mira'
Cardinality comes from the business rule, and today's data can mislead. Every user in a sample may have one shipping address while the rule allows 5. Model the rule: ask the people who own the process how many are allowed, then choose the shape. Changing one-to-many into many-to-many later means a new table and a rewrite of every query that joined the old column.

Required vs Optional

Daily Life
Interviews
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 an author. Some posts have a club.
CREATE TABLE posts (
post_id BIGINT NOT NULL,
author_id BIGINT NOT NULL,
club_id BIGINT,
body VARCHAR,
created_at TIMESTAMP NOT NULL
)
post_idauthor_idclub_idbody
90011017Launch day
9002101NULLDay 2 numbers
90031038Hello

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.

SELECT
p.post_id,
p.body,
c.name AS club_name
FROM posts AS p
LEFT JOIN clubs AS c
ON p.club_id = c.club_id
post_idbodyclub_name
9001Launch dayFounders
9002Day 2 numbersNULL
9003HelloRunners
Every join along an optional relationship is a decision about the unmatched rows. Keep them with a left join, or drop them on purpose with an inner join.

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.

A required minimum on the many side is enforced by the process that writes the rows, and verified by a check that runs after each load. This query returns every club that breaks the rule.
SELECT
c.club_id,
c.name
FROM clubs AS c
LEFT JOIN memberships AS m
ON m.club_id = c.club_id
WHERE m.club_id IS NULL
Minimum and maximum together give 4 readings for one end of a relationship.
MinimumMaximumRead asExample
01zero or oneA post may sit in one club
11exactly oneA post has one author
0manyzero or moreA user may write any number of posts
1manyone or moreA club needs at least one member

Deciding: can the row stand alone?

Test each relationship with one question: if the other row never existed, or was deleted, would this row still mean something? A post without an author is noise, so the author is required. A post without a club is still a post, so the club is optional. The same answer settles what a delete does. Call the row being pointed at the parent, and the row holding the key the child.
Required (NOT NULL)
  • 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
Optional (nullable)
  • Deleting the parent can set the key to NULL and keep the child
  • Inner joins drop the unmatched rows, left joins keep them
TIP
2 shortcuts to refuse. Marking a required key optional because the source sometimes delivers it late leaks NULLs into every consumer. Marking an optional key required forces writers to invent a fake value such as author_id 0, which joins to nothing or to a made-up row.
Multiple Choice

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?

Required and optional are claims about the business, written into the schema. Each one decides insert order, delete behavior, and which join is safe. When the claim is uncertain, ask what the row would mean alone, then write the answer down next to the column.

Self-Referential Tables

Daily Life
Interviews
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.

The app's comments table holds the thread under post 9001.

comment_idauthor_idparent_comment_idbody
501102NULLCongrats!
502101501Thanks dev
503103502Well earned
504103NULLWhat comes next?
505102501Party 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.

SELECT
c.comment_id,
c.body,
p.body AS parent_body
FROM comments AS c
LEFT JOIN comments AS p
ON c.parent_comment_id = p.comment_id

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

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 starts from a set of rows, then repeats one step, adding rows that connect to what it already has, until a round adds nothing.
WITH RECURSIVE thread(comment_id, parent_comment_id, depth) AS (
SELECT
comment_id,
parent_comment_id,
1
FROM comments
WHERE parent_comment_id IS NULL
UNION ALL
SELECT
c.comment_id,
c.parent_comment_id,
t.depth + 1
FROM comments AS c
JOIN thread AS t
ON c.parent_comment_id = t.comment_id
)
SELECT
comment_id,
depth
FROM thread
ORDER BY depth, comment_id
RoundRows addedWhy
1501, 504parent is NULL
2502, 505parent is 501
3503parent is 502
4noneno comment replies to 503
Each round's rows get a depth equal to the round number, so 503 comes out at depth 3. The query never names a depth limit. It stops because round 4 finds no comment whose parent is 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.

users
user_idPKBIGINT
handleVARCHAR
friendships
user_idFKBIGINT
friend_idFKBIGINT
created_atTIMESTAMP

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.

Multiple Choice

The author of comment 501 deletes it. Rows 502 and 505 keep parent_comment_id = 501. Which rows does the recursive query return now?

A self-referential table is the one-to-many and optional rules pointed back at one table. The new work is in the reading: aliases for the roles, a recursive walk for unknown depth, and checks for loops and orphans.

Complex Patterns

Daily Life
Interviews
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

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_iduser_idtarget_typetarget_id
1102post9001
2103comment501
3101comment501

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.

2 other designs keep declared foreign keys.
DesignOne row meansBreaks when
Type and id columnsA like on any target, named by a stringA target is deleted or a type is misspelled
One nullable key per targetA like with post_id or comment_id filledA row fills both keys or neither
One table per targetA like on a post, or on a comment, by tableA question spans targets, such as all likes by one user
Likes for more than postsStep 1
>

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.

likes
like_idBIGINTPKuser_idBIGINTFKpost_idBIGINTFK
posts
post_idBIGINTPKauthor_idBIGINTFK
comments
comment_idBIGINTPKparent_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.

users
user_idPKBIGINT
handleVARCHAR
pinned_post_idFKBIGINT
posts
post_idPKBIGINT
author_idFKBIGINT
bodyVARCHAR

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.

SELECT
u.user_id,
u.pinned_post_id,
p.author_id
FROM users AS u
JOIN posts AS p
ON u.pinned_post_id = p.post_id
WHERE p.author_id != u.user_id
Both patterns come down to the same move. Find the promise the plain foreign key was making, see which part the new design drops, and give that part to a declared key, a nullable column, or a scheduled check.
PUTTING IT ALL TOGETHER

> 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.

State each connection as a sentence first: a seller publishes listings, an order contains listings. The nouns become tables and each verb becomes a key.
An order holds many listings and a listing appears in many orders, so order_items is a junction table, and its quantity column belongs to the connection.
The 8% gap is an inner join along an optional key: guest orders carry a NULL buyer_id, and a left join brings them back.
The category tree is one table with a nullable parent_category_id, and a recursive walk from the roots gives every category its depth.
A review of a seller or a listing is polymorphic: choose declared keys, or a type and id pair backed by an orphan check.
Sellers and payout accounts point at each other. Make default_payout_account_id nullable and the load order becomes sellers, accounts, then the update.
KEY TAKEAWAYS
A relationship is a matching key value. State it as a sentence in both directions before drawing a table.
Cardinality places the key: on the many side for one-to-many, unique for one-to-one, in a junction table for many-to-many.
Required means NOT NULL. Optional means every join along the key decides what happens to the unmatched rows.
A hierarchy is an optional one-to-many from a table to itself, read with aliases and a recursive walk.
Polymorphic and circular designs drop a promise the plain foreign key made. Give that promise to a declared key or a scheduled check.

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

  1. 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.

  2. 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

  3. 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

  4. 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

  5. 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