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 65/ 160
04. Subqueries & Common Table Expressions (CTEs)

Performance Trade-offs: Subqueries vs Joins

Choose joins or subqueries based on readability and planner behavior.

IntermediatePlanner Choice · Semi-Join Rewrite3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Joins and subqueries can ask the same question. The database often runs them the same way, but joins can repeat rows and subqueries don't.

Think of it like…

Asking a librarian "do you have any books by this author?" versus "bring me every book by this author". The first stops at one; the second brings a pile. A good librarian may fetch the answer the same way, but the results are different shapes.

Where you’ve seen it

"Customers who bought something this month": WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.created_at >= '2026-11-01') returns each customer once. The JOIN version returns a customer once per order, so it needs DISTINCT, which does extra work.

Words you’ll hear

Semi-join rewrite
The optimizer turning IN/EXISTS into a join that stops at the first match.
Scalar subquery in SELECT
A subquery evaluated for each output row; can be slow if not flattened.
Derived table
A subquery in FROM, often used to pre-aggregate before joining.
Plan equivalence
Different SQL texts producing the same execution plan.

Visual diagram

Loading interactive diagram

Theory & example queries

When they really are the same

PostgreSQL, SQL Server, Oracle and MySQL 8 all turn IN (subquery) and correlated EXISTS into semi-joins, so the choice between them, and often against an equivalent join, is mostly about readability. MySQL before 5.6 handled IN subqueries badly, which is where much of the "always use joins" folklore comes from.

Choose based on what the query means: existence checks read best as EXISTS; if you need columns from the other table, you need a join; to compare against an aggregate, use a derived table or CTE.

Two ways, one planQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  customers5WHERE6  id IN (7    SELECT8      customer_id9    FROM10      orders11  )
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/11
query.sql
1SELECT2  *3FROM4  customers c5WHERE6  EXISTS (7    SELECT8      19    FROM10      orders o11    WHERE12      o.customer_id = c.id13  )
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/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative EXPLAIN shape
Hash Semi Join Hash Cond: (customers.id = orders.customer_id) -> Seq Scan on customers -> Hash -> Seq Scan on orders

Note: EXPLAIN is illustrative. The optimizer may choose Hash Semi Join, a nested loop, or another equivalent plan based on statistics and indexing.

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

and

typically both show a Hash Semi Join in EXPLAIN.

Key takeaway: For IN/EXISTS, write what reads clearly; the optimizer usually converges.

Patterns that do differ

Joins to one-to-many tables duplicate rows, and patching that with DISTINCT costs a sort or hash over the larger result. A correlated scalar subquery in SELECT, such as (SELECT MAX(created_at) FROM orders o WHERE o.customer_id = c.id), can run once per row if the optimizer can't decorrelate it; with an index on the correlation column it's fine for small results, but over millions of rows a join to a grouped subquery is usually faster.

NOT IN against a nullable column is semantically wrong (it returns nothing when the subquery has a NULL) and often plans worse than NOT EXISTS. Whatever you write, EXPLAIN ANALYZE is the tie-breaker, not rules of thumb.

Per-row subquery vs one grouped joinQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.id,3  o.last_order4FROM5  customers c6  LEFT JOIN (7    SELECT8      customer_id,9      MAX(created_at) AS last_order10    FROM11      orders12    GROUP BY13      customer_id14  ) o ON o.customer_id = c.id;
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.
Customers with their latest order3 sample rows
Customers with their latest order
idlast_order
12026-11-19 14:20:00
2NULL
32026-11-21 09:05:00

Note: Assumes customer 2 has no order; the grouped subquery computes MAX(created_at) once per customer_id.

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

Instead of a scalar subquery per customer,

aggregates orders once.

Key takeaway: Watch for duplication, per-row scalar subqueries and NOT IN; then measure.

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

Say what you need back

Only rows of one table that have (or lack) a match? Use EXISTS / NOT EXISTS. Columns from both tables? Use a join.

SQL at this stepReadable preview
1existence → EXISTS · columns →2JOIN
What to watch at this step
Start from
meaning
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Many queries can be written either with a subquery (WHERE id IN (SELECT …), EXISTS) or with a JOIN. Modern optimizers often rewrite one into the other, so for IN and EXISTS the plans are frequently identical. The real differences are in meaning (joins can duplicate rows; NOT IN breaks on NULLs) and in a few patterns that optimizers can't flatten.

Why it matters: "Is a join faster than a subquery?" is a perennial interview question, and the honest answer is "it depends; check the plan". Knowing which patterns are genuinely slow (per-row scalar subqueries, NOT IN with NULLs) and which are just style lets you write clear SQL without guessing.

When to reach for it

  • EXISTS for "has at least one" filters
  • Joins when you need related columns
  • Derived tables to pre-aggregate before joining

When to avoid or be careful

  • JOIN + DISTINCT as an existence check
  • NOT IN against nullable columns
  • Believing "joins are always faster" without checking the plan

Subquery forms vs joins

EXISTS / IN subquery
Best for: Filtering rows by whether a related row exists

Strengths: No duplicate rows; usually planned as a semi-join.

Watch out: Can't return columns from the subquery's table.

JOIN
Best for: Needing columns from both tables

Strengths: Flexible; the optimizer can reorder it freely.

Watch out: One-to-many joins duplicate rows.

Scalar subquery in SELECT
Best for: One related value per row in small result sets

Strengths: Reads naturally.

Watch out: May execute per row on large results.

Interview signals & numbers to know

When this topic comes up

  • “Which is faster, a join or a subquery?”
  • SubPlan in EXPLAIN output
  • A query that needs DISTINCT after a join
  • NOT IN performance
  • Rewriting a slow correlated subquery

Benchmarks & rules of thumb

MySQL 5.6 -
when IN-subquery optimisation improved
1 match -
is enough for a semi-join to stop
Per row -
worst case for an un-flattened scalar subquery

Common mistakes & follow-ups

Common interview mistakes

  • Rewriting every subquery as a join and then adding DISTINCT to remove the duplicates it created.
  • Using NOT IN and getting no results when the subquery contains NULL.
  • Claiming one form is always faster instead of checking EXPLAIN.

Likely interviewer follow-ups

  • Do IN and EXISTS perform differently in PostgreSQL?
  • When would a correlated subquery in SELECT be slow, and how would you rewrite it?
  • Why might a JOIN return more rows than the equivalent IN subquery?
Interview tip: Answer with "often the same plan in modern optimizers", then name the cases where they differ: duplication, NOT IN with NULLs, per-row scalar subqueries. Finish with "I'd confirm with EXPLAIN". It's a nuanced answer that beats any rule of thumb.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Performance Trade-offs: Subqueries vs Joins with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Correlated Subqueries vs Non-Correlated Subqueries
Next topic
Introduction to Common Table Expressions (WITH Clause)