Learn SQL
-- subqueries.in_exists

IN & EXISTS in SQL

Membership tests against another query’s results

--concept

WHERE x IN (SELECT …) asks “is x one of the values that query returned?”; WHERE EXISTS (SELECT …) asks “does that query return any row at all (for this row)?”. Both replace hand-managed id lists with a live query, and both usually optimise to the same semi-join. EXISTS is the safer habit for correlated tests because it short-circuits on the first match.

--how it works
1

IN tests membership

WHERE department IN (SELECT dept_id FROM …) — for each outer row, is the value among the subquery’s results?

2

EXISTS tests existence

WHERE EXISTS (SELECT 1 FROM … WHERE …) — is there any matching row for this outer row? The select list is ignored.

3

Correlation shapes the choice

Uncorrelated list of known values → IN. Per-row probe that mentions the outer row → EXISTS, which stops at the first match.

4

Negation: NOT EXISTS is the safe one

NOT IN returns zero rows if the subquery yields a single NULL (three-valued logic). NOT EXISTS has no such trap — default to it.

5

Engines converge anyway

Modern optimisers rewrite both into semi/anti joins; pick the form that states your intent most clearly.

--visualization
short-circuits on first hit
departments (outer)Engineering…Sales…Marketing…EXISTS (SELECT 1 FROM employees eWHERE e.department = d.dept_id AND e.salary > 80000)waiting…result builds up as probes finish…semi-join: each outer row kept at most once
Stage 1 / 6
Outer query: every department. For each one the engine runs the correlated EXISTS probe: does anyone here earn over 80,000?
--example
query.sql
1SELECT dept_id, location
2FROM departments d
3WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id AND e.salary > 80000);
Result
dept_idlocation
EngineeringBerlin

For each department the engine asks: does anyone here earn over 80,000? Sales peaks at 58,000 and Marketing at 47,000, so only Engineering survives. The SELECT 1 is convention — EXISTS never looks at the select list.

--variants

IN with a subquery

Employees in departments that have a location tracked.

query.sql
1SELECT name, department
2FROM employees
3WHERE department IN (SELECT dept_id FROM departments WHERE location IS NOT NULL);
Result
namedepartment
AliceEngineering
BobSales
CynthiaEngineering
DavidMarketing
ElenaSales
FaridEngineering
1Inner query: Engineering, Sales, Marketing — all have locations.
2Every employee’s department appears in that list, so everyone survives.
3If one department had NULL location, its employees would drop out — exactly the filter working.

EXISTS — probe per row

Departments that currently employ someone.

query.sql
1SELECT d.dept_id, d.location
2FROM departments d
3WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
Result
dept_idlocation
EngineeringBerlin
SalesMadrid
MarketingLisbon
1For each department, the correlated probe looks for any employee with that department.
2All three find matches, so all three rows return — the SELECT 1 is never examined.
3The engine stops at the first hit; on big tables the index on e.department makes each probe cheap.

NOT EXISTS — the anti-join

Departments with no employees at all.

query.sql
1SELECT d.dept_id
2FROM departments d
3WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
4-- with a Research row present: returns Research
Result
dept_id
Research
1NOT EXISTS keeps outer rows for which the probe finds nothing.
2No NULL-trap: a NULL department value in employees simply matches nothing.
3This is the canonical “find children without parents / parents without children” query.

NOT IN meets NULL

One NULL in the subquery empties the whole result.

query.sql
1SELECT name FROM employees
2WHERE department NOT IN (SELECT dept_id FROM departments WHERE dept_id <> 'Sales' OR 1 = 1);
3-- variant: subquery containing NULL
4SELECT name FROM employees
5WHERE department NOT IN (SELECT NULLIF(dept_id, 'Engineering') FROM departments);
Result
name
(0 rows)
1If the inner list contains NULL, x NOT IN (…) can never be TRUE — UNKNOWN is not a pass.
2Every row is silently filtered out; no error, just an empty result that “cannot be true”.
3Rule: NOT EXISTS for negated tests, or ensure the inner column is NOT NULL.
--key facts
NOT IN + NULLone NULL in the subquery makes NOT IN return zero rows — prefer NOT EXISTS
SELECT 1 conventionEXISTS ignores the select list; anything (even NULL) works
Semi-jointhe engine plan keeps each outer row at most once, no row multiplication
--use cases
Referential spot-checks: children without parents (NOT EXISTS)
Feature audience logic: users in cohort A who also appear in cohort B
Blacklist/whitelist filtering against a live table rather than a hardcoded list
Semi-join reporting: “which categories have products?” without duplicating rows
--under the hood
Both forms usually compile to the same semi-join; planner statistics decide the probe order.
EXISTS short-circuits per row, so for correlated probes against indexed columns it can beat a materialised IN list on very large inputs.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.