Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

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
Data Science topics
Lesson 26/ 160
02. SQL & Data Engineering Basics

Subqueries & Nested Queries

Use scalar, correlated, and IN/EXISTS subqueries when joins alone are awkward.

IntermediateScalar Subquery · Correlated3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A subquery is a small question asked inside a bigger question, like "is this customer in the list of people who returned something?".

Think of it like…

Checking a guest list against another list: "is this person on the VIP list?" (IN / EXISTS) or "is this person NOT on the cancellations list?" (NOT EXISTS). You don't merge the lists; you just ask a yes/no question per guest.

Where you’ve seen it

To build a retention label, the analyst needs customers who purchased in January but not in February. SELECT c.customer_id FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.created_at >= '2026-01-01' AND o.created_at < '2026-02-01') AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.created_at >= '2026-02-01' AND o.created_at < '2026-03-01') returns each customer once. The earlier version with NOT IN (SELECT customer_id …) returned zero rows because one February order had a NULL customer_id.

Words you’ll hear

Scalar subquery
Returns exactly one value; usable like a constant in expressions.
EXISTS / NOT EXISTS
True/false test for whether the subquery returns any row; NULL-safe.
Correlated subquery
References columns of the outer query, evaluated per outer row (logically).
NOT IN trap
If the list contains NULL, NOT IN never evaluates to true.

Visual diagram

Loading interactive diagram

Theory & deep dive

Kinds of subqueries and when to use them

Scalar subqueries compare rows with a global value: WHERE amount > (SELECT AVG(amount) FROM orders); they must return one row and one column or the query errors. IN tests membership in a list or subquery (customer_id IN (SELECT customer_id FROM returns)). EXISTS asks whether any matching row exists (EXISTS (SELECT 1 FROM returns r WHERE r.order_id = o.order_id)), which is robust against duplicates and NULLs and often as fast as or faster than IN. A correlated subquery such as amount > (SELECT AVG(amount) FROM orders o2 WHERE o2.category = o.category) compares each order with its own category's average; databases often rewrite it as a join, but on large tables a window function (AVG(amount) OVER (PARTITION BY category)) is clearer and faster.

Derived tables (FROM (SELECT ... ) AS t) let you aggregate first and join the result, avoiding fan-out. For readability, prefer CTEs over deeply nested subqueries.

Orders above their category average

SELECT order_id, category, amount FROM (SELECT *, AVG(amount) OVER (PARTITION BY category) AS cat_avg FROM orders) t WHERE amount > cat_avg; The window version replaces a correlated subquery and reads the table once.

Key takeaway: Scalar for constants, EXISTS for membership, windows instead of heavy correlated subqueries.

NULL traps and pandas equivalents

x NOT IN (1, 2, NULL) is never true, because comparing x with NULL is unknown, so a single NULL in the subquery's column makes NOT IN return no rows. Use NOT EXISTS (or filter the subquery with WHERE col IS NOT NULL) for anti-joins. IN doesn't have the problem for matches, since a NULL simply never matches. Make this a rule: for "not in" logic, use NOT EXISTS.

In pandas, df[df.customer_id.isin(returns.customer_id)] mirrors IN, ~isin mirrors NOT IN (with no NULL trap, but NaN handling differs), and an anti-join is df.merge(other, on="key", how="left", indicator=True).query("_merge == 'left_only'"). Be consistent about how missing keys are treated, and verify cohort sizes: the count of the cohort plus the count of its complement should equal the base population.

Anti-join in pandas

m = jan.merge(feb, on="customer_id", how="left", indicator=True); lapsed = m[m["_merge"] == "left_only"] gives January buyers who didn't buy in February; len(lapsed) + len(retained) == len(jan) checks the split is complete.

Key takeaway: Use NOT EXISTS for anti-joins; check that cohort and complement add up.

How it works, step by step

Step 1 of 4
Define

1. State the membership question

Write the cohort as a yes/no condition per entity: bought in January and not in February.

EXISTS(Jan) AND NOT EXISTS(Feb)
Key numbers at this step
Window
half-open dates

When to use it & trade-offs

What it is

A subquery is a SELECT inside another query. A scalar subquery returns one value (amount > (SELECT AVG(amount) FROM orders)); an IN / NOT IN subquery returns a list to test membership; EXISTS / NOT EXISTS returns true if any row matches; a correlated subquery refers to the outer row and runs once per row logically; and a derived table is a subquery in FROM. In data work they define cohorts (customers who did X), anti-cohorts (who didn't) and comparisons to a global statistic, without joining and risking duplicate rows.

Why it matters: Many analysis questions are set membership questions: customers who bought but never returned, users active in March but not April, orders above the category average. EXISTS and NOT EXISTS answer them safely, while joins can multiply rows. The NOT IN trap (a NULL in the list makes the whole condition return nothing) is a classic source of silently empty results.

When to reach for it

  • Defining cohorts and anti-cohorts
  • Filtering by a global statistic
  • Anti-joins for churn and gap analysis

When to avoid or be careful

  • NOT IN against columns that may contain NULL
  • Correlated subqueries over huge tables when a window works
  • Deeply nested subqueries instead of CTEs

Subquery constructs

EXISTS / NOT EXISTS
Best for: Membership and anti-join logic

Strengths: NULL-safe; no duplicates; can stop early.

Watch out: Slightly verbose.

IN / NOT IN
Best for: Short lists and simple membership

Strengths: Concise.

Watch out: NOT IN breaks with NULLs.

Scalar / correlated subquery
Best for: Comparing to a global or per-group statistic

Strengths: Readable for simple cases.

Watch out: Correlated versions can be slow; windows are often better.

Interview signals & numbers to know

When this topic comes up

  • “Customers who did X but not Y”
  • “NOT IN returns nothing”
  • “Orders above the category average”
  • Anti-joins
  • Cohort definitions

Benchmarks & rules of thumb

0 rows -
NOT IN result when the list contains a NULL
1 value -
a scalar subquery must return
cohort + complement -
must equal the base population

Common mistakes & follow-ups

Common interview mistakes

  • Using NOT IN (SELECT customer_id …) when customer_id can be NULL and getting an empty result.
  • Writing a correlated subquery over 100 million rows when a window function would scan once.
  • Not checking that the retained and lapsed groups sum to the January cohort.

Likely interviewer follow-ups

  • Why does NOT IN fail when the list contains NULL?
  • How would you find users active in March but not April?
  • When would you replace a correlated subquery with a window function?
Interview tip: Say "I'd use NOT EXISTS" for any "did not" question. It signals you know the NULL trap without being asked.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Subqueries & Nested Queries with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Self Joins & Cross Joins
Next topic
Common Table Expressions (CTEs)