Performance Trade-offs: Subqueries vs Joins
Choose joins or subqueries based on readability and planner behavior.
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
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.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT *FROM customersWHERE id IN ( SELECT customer_id FROM orders )PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
SELECT *FROM customers cWHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id )PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative EXPLAIN shape
Note: EXPLAIN is illustrative. The optimizer may choose Hash Semi Join, a nested loop, or another equivalent plan based on statistics and indexing.
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.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT c.id, o.last_orderFROM customers c LEFT JOIN ( SELECT customer_id, MAX(created_at) AS last_order FROM orders GROUP BY customer_id ) o ON o.customer_id = c.id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Customers with their latest order3 sample rows
| id | last_order |
|---|---|
| 1 | 2026-11-19 14:20:00 |
| 2 | NULL |
| 3 | 2026-11-21 09:05:00 |
Note: Assumes customer 2 has no order; the grouped subquery computes MAX(created_at) once per customer_id.
Instead of a scalar subquery per customer,
aggregates orders once.
Key takeaway: Watch for duplication, per-row scalar subqueries and NOT IN; then measure.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
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.
existence → EXISTS · columns →JOINWhen 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
Strengths: No duplicate rows; usually planned as a semi-join.
Watch out: Can't return columns from the subquery's table.
Strengths: Flexible; the optimizer can reorder it freely.
Watch out: One-to-many joins duplicate rows.
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?
Knowledge check
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.