Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 41/ 160
03. Joins & Relational Querying

Understanding Relationships (One-to-One, One-to-Many, Many-to-Many)

Model 1:1, 1:N, and M:N relationships before writing join queries.

BeginnerOne-to-One · One-to-Many3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

One thing matches one thing, one thing has many things, or many things match many things. The last kind needs an extra table to list the pairs.

Think of it like…

A country has one capital (one-to-one), a mother can have many children but each child has one birth mother (one-to-many), and authors write many books while books can have many authors (many-to-many, recorded in a separate list of author-book pairs).

Where you’ve seen it

An e-commerce schema: users 1–1 user_settings (UNIQUE user_id), customers 1–N orders (orders.customer_id), and products N–M categories through product_categories(product_id, category_id), because a product can be in several categories and a category holds many products.

Words you’ll hear

Cardinality
How many rows on one side can relate to a row on the other: 1:1, 1:N, M:N.
Foreign key placement
In 1:N the key goes on the many side; in 1:1 on either side, made UNIQUE.
Junction table
A table of (a_id, b_id) pairs that represents a many-to-many relationship.
Optional vs required
A nullable foreign key means the relationship is optional.

Visual diagram

Loading interactive diagram

Theory & example queries

Modelling each type

One-to-many is the most common. Put the foreign key on the many side (orders.customer_id), because each order has exactly one customer while a customer can't hold a list of order ids in one column. Make it NOT NULL if every child must have a parent.

One-to-one is a one-to-many with a UNIQUE constraint on the foreign key, or two tables sharing the same primary key. It's used to split optional or rarely read columns into their own table. Many-to-many can't be represented with a single foreign key: create a junction table with a foreign key to each side and a composite primary key so a pair can't repeat.

A many-to-many junction tableQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE enrolments (2  student_id bigint REFERENCES students (id),3  course_id bigint REFERENCES courses (id),4  enrolled_at date NOT NULL,5  PRIMARY KEY (student_id, course_id)6);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Junction table created
CREATE TABLE

Note: Creation succeeds when referenced students and courses tables already exist and enrolments is unused.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: 1:N → FK on the many side; 1:1 → UNIQUE FK; M:N → junction table.

How relationships affect queries

Joining from the one side to the many side repeats the parent for every child: one customer with 12 orders gives 12 rows. That's expected, but it's why aggregates over joined data need care, and why joining a parent to two different many-side tables multiplies rows (fan-out).

Junction tables often carry facts about the relationship itself, such as enrolled_at or a grade. That's normal: the junction row is the enrolment. Ask what one row of each table means, and the relationship type usually becomes obvious.

Students in a courseQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.name3FROM4  courses c5  JOIN enrolments e ON e.course_id = c.id6  JOIN students s ON s.id = e.student_id7WHERE8  c.code = 'DB101';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Students enrolled in DB1013 sample rows
Students enrolled in DB101
name
Asha Rao
Kabir Shah
Mei Chen

Note: Representative enrollment data for course code DB101.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Joining across the many side repeats rows; junction rows can hold their own facts.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Analysis

Ask both directions

For entities A and B, ask how many B one A can have, and how many A one B can have. The two answers give the type.

Focus at this step

1 customer → many orders · 1 order → 1 customer

What to watch at this step
Result
one-to-many
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Tables relate in three ways. One-to-one: each row matches at most one row on the other side (a user and their profile). One-to-many: one parent has many children (a customer and their orders), with the foreign key on the "many" side. Many-to-many: rows on both sides relate to many on the other (students and courses), which needs a junction table holding pairs of foreign keys.

Why it matters: Getting the relationship type right decides where foreign keys go, which joins duplicate rows, and whether the design can represent reality at all. It's the first step of every schema-design interview question, and most join bugs trace back to misjudging it.

When to reach for it

  • Designing any schema before writing queries
  • Deciding where a foreign key column belongs
  • Explaining why a join returns more rows than expected

When to avoid or be careful

  • Putting a list of child ids in the parent row
  • Modelling a many-to-many with a foreign key on one side only
  • Splitting tables 1:1 without a reason (optional or rarely used columns)

Ways to model a many-to-many relationship

Junction table
Best for: Every relational many-to-many

Strengths: Enforced by foreign keys, indexable both ways, can hold relationship facts.

Watch out: An extra table and join.

Array or JSON of ids in one table
Best for: Small, read-only lists where integrity doesn't matter

Strengths: No join for simple reads.

Watch out: No foreign keys, awkward queries from the other side.

Comma-separated ids
Best for: Nothing

Strengths: Easy to write once.

Watch out: Breaks 1NF, can't be indexed or validated.

Interview signals & numbers to know

When this topic comes up

  • “Design the schema for …”
  • “One-to-many vs many-to-many”
  • “Where does the foreign key go?”
  • Junction / bridge / association table
  • Students and courses, authors and books

Benchmarks & rules of thumb

3 -
relationship types
2 -
foreign keys in a junction table
N rows -
per parent when joining to its N children

Common mistakes & follow-ups

Common interview mistakes

  • Adding order_ids to the customers table instead of customer_id to orders.
  • Treating a many-to-many as one-to-many, so a product can only belong to one category.
  • Forgetting the composite primary key on a junction table, allowing the same pair to be stored twice.

Likely interviewer follow-ups

  • How would you model users following other users?
  • When would you split a table into two with a one-to-one relationship?
  • What extra columns might a junction table need?
Interview tip: Ask the two-direction question out loud for each pair of entities. It turns schema design into a quick, systematic exercise and shows the interviewer your reasoning.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Understanding Relationships (One-to-One, One-to-Many, Many-to-Many) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Writing Clean, Readable & Maintainable SQL Style Guides
Next topic
Bridge / Junction Tables for Many-to-Many Relationships