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 60/ 160
03. Joins & Relational Querying

Visualizing & Debugging Complex Multi-Join Queries

Debug complex joins by checking grain, row counts, and intermediate CTEs.

IntermediateRow Count Checks · Intermediate CTEs3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Add one table at a time and count the rows after each step; the step where the count goes wrong is the bug.

Think of it like…

Finding a leak in a long pipe by measuring the water flow at each joint: the joint where the flow suddenly changes is where the problem is.

Where you’ve seen it

A marketing report shows 18,400 conversions but the product team counts 12,100. Splitting the query into CTEs and counting each shows sessions → campaigns is fine, but joining campaign_costs, which has one row per campaign per channel, duplicates every conversion from campaigns that ran on two channels. Aggregating costs per campaign before the join brings the count back to 12,100.

Words you’ll hear

Grain check
Verifying a table's supposed key really is unique: GROUP BY key HAVING COUNT(*) > 1.
Row-count ledger
The row count after each join, written down step by step.
Fan-out
A join that multiplies rows because the right side has several matches per key.
Silent drop
Rows lost to an INNER JOIN or a WHERE condition on an outer-joined table.

Visual diagram

Loading interactive diagram

Theory & example queries

Check grain, then count step by step

Start with the inputs. For each table, write down the key you believe makes a row unique and test it: SELECT campaign_id, COUNT(*) FROM campaign_costs GROUP BY campaign_id HAVING COUNT(*) > 1 LIMIT 10; If rows come back, joining on campaign_id alone will fan out. Then rebuild the query as a chain of CTEs, one join per CTE, and select COUNT(*) and COUNT(DISTINCT driving_key) from each.

Interpret the ledger: if COUNT(*) grows while COUNT(DISTINCT key) stays the same, a join produced several matches per key (fan-out). If COUNT(DISTINCT key) falls, rows were dropped: an INNER JOIN with missing matches, or a WHERE condition on a LEFT-joined table that turned it into an inner join. Fix the step, re-run the ledger, and only then look at the metrics.

A ledger in one queryQuery 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.sqlReadable preview
1WITH s12AS (3SELECT …4FROM conversions),5  s26AS (7SELECT …8FROM s19JOIN campaigns …),10  s311AS (12SELECT …13FROM s214JOIN campaign_costs …)15SELECT 's1',16  COUNT(*),17  COUNT(DISTINCT conversion_id)18FROM s1 UNION ALL19SELECT 's2',20  COUNT(*),21  COUNT(DISTINCT conversion_id)22FROM s2 UNION ALL23SELECT 's3',24  COUNT(*),25  COUNT(DISTINCT conversion_id)26FROM s3;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/26
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
stagerowsconversion_ids
s110001000
s215001000
s31480980

Note: Illustrative diagnostic counts: s2 introduces fan-out, while s3 drops 20 distinct conversions after another join.

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

Key takeaway: COUNT(*) up with distinct keys flat = fan-out; distinct keys down = dropped rows.

Other usual suspects

Key mismatches: joining a text column to an integer, codes with different case, trailing spaces, or ids that are padded in one system ('00042' vs '42'). These make matches disappear without an error; spot them by checking unmatched keys with a LEFT JOIN … IS NULL and looking at sample values. Wrong join column: joining on name instead of id, or on the wrong date (created vs shipped).

Filter placement: a right-table condition in WHERE after a LEFT JOIN removes the unmatched rows you wanted to keep. Many-to-many paths: two child tables joined through the same parent multiply each other. For performance problems rather than wrong results, EXPLAIN ANALYZE shows where estimated and actual row counts diverge, which is often the same join that's logically wrong.

Finding keys that don't matchQuery example
1Input dataStart from the source rows or state that the statement sees.
sessions
2 rows
sessions sample rows
iduser_idlast_seen_atactive
112026-11-21 09:00true
222026-11-20 18:30false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.campaign_code,3  COUNT(*)4FROM5  sessions s6  LEFT JOIN campaigns c ON c.code = s.campaign_code7WHERE8  c.code IS NULL9GROUP BY10  111ORDER BY12  2 DESC13LIMIT14  20;
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/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
campaign_codecount
Summer_Sale 184
BLACK_FRIDAY73
NULL21

Note: Illustrative unmatched session codes; trailing spaces, case differences and NULL values can each produce orphan groups.

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

Values like 'Summer_Sale ' with a trailing space show up immediately.

Key takeaway: Check key types and formats, filter placement and many-to-many paths.

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

Draw the join graph

List the tables and label each join 1:1, 1:N or N:M from the driving table's point of view.

Focus at this step

conversions 1:1 campaigns 1:N campaign_costs

What to watch at this step
Look for
1:N and N:M
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

When a query with five or six joins returns the wrong numbers or too many or too few rows, debug it the way you'd debug code: break it into steps and check each one. Confirm the grain (unique key) of every input table, add joins one at a time while recording the row count, and look for the step where the count jumps (fan-out) or drops (an inner join or WHERE filtering rows away). Drawing the join graph with 1:1, 1:N and N:M labels usually reveals the culprit.

Why it matters: Wrong numbers from a big join rarely produce an error; they produce a dashboard nobody trusts. A systematic method finds the problem in minutes instead of hours of staring at SQL, and interviewers increasingly ask "this query's total is wrong, how would you find out why?" to test exactly that.

When to reach for it

  • Reports whose totals don't match another team's numbers
  • Reviewing a colleague's long query
  • Before shipping a new dashboard

When to avoid or be careful

  • Adding DISTINCT until the numbers look right
  • Debugging the final aggregate instead of the joins
  • Assuming a column is unique without checking

Debugging techniques for complex joins

Row-count ledger with CTEs
Best for: Wrong totals or row counts

Strengths: Pinpoints the exact join that misbehaves.

Watch out: Takes a few minutes to restructure the query.

Grain checks on inputs
Best for: Before writing or reviewing any multi-join query

Strengths: Catches fan-out before it happens.

Watch out: Needs knowing which key each table should have.

EXPLAIN ANALYZE
Best for: Slow queries and bad estimates

Strengths: Shows actual rows per plan node.

Watch out: Explains cost, not whether the business logic is right.

Interview signals & numbers to know

When this topic comes up

  • “Our numbers don't match finance”
  • “The query returns more rows than expected”
  • “Rows are missing after adding a join”
  • Reviewing complex SQL
  • Data quality

Benchmarks & rules of thumb

0 -
rows expected from a grain check
2 counts -
COUNT(*) and COUNT(DISTINCT key) per step
1 join -
added per debugging step

Common mistakes & follow-ups

Common interview mistakes

  • Slapping SELECT DISTINCT on the final result, which hides the fan-out and leaves the SUMs wrong.
  • Assuming campaign_id is unique in campaign_costs when it's unique per campaign per channel.
  • Missing that a text join key has trailing spaces in one table.

Likely interviewer follow-ups

  • A report's revenue is 40% higher than finance's. How do you find out why?
  • How do you tell fan-out apart from dropped rows?
  • What causes a join to silently match fewer rows than expected?
Interview tip: Describe the method (join graph, grain checks, ledger, fix, re-check) before diving into SQL. A clear process is what interviewers are really asking for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Visualizing & Debugging Complex Multi-Join Queries with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Deduplicating Rows Using Self Joins
Next topic
Scalar Subqueries (Single Value in SELECT or WHERE)