01 / 21

Subqueries in
WHERE

Master the art of nesting queries inside WHERE clauses using IN and EXISTS to filter rows with powerful, dynamic conditions.

SQL

What Is a Subquery?

A subquery (also called an inner query or nested query) is a complete SELECT statement placed inside another SQL statement. It runs first, produces a result, and that result is used by the outer query.

Anatomy of a Nested Query

OUTER QUERY SELECT name, grade FROM students WHERE grade
\( > \)
INNER QUERY (runs first) SELECT AVG (grade) FROM students ( result flows up

Why Subqueries Matter

Dynamic Filtering
Filter based on computed values (averages, counts) instead of hard-coding numbers.
Cross-Table Logic
Check conditions against data in a completely different table without a full JOIN.
Readable Queries
Break complex logic into clear, self-contained steps that read like English.

Subqueries with IN

IN checks whether a value matches any value in the list returned by the subquery. The inner query must return a single column.

SELECT name FROM employees WHERE department_id IN ( SELECT id FROM departments WHERE location = 'New York' );

Subqueries with EXISTS

EXISTS checks whether the subquery returns at least one row. It does not care about the actual values: it only tests for existence.

SELECT name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );

IN vs EXISTS: Key Distinction

IN EXISTS
Returns A list of values TRUE or FALSE
Correlated? Usually not Usually yes
NULL handling NULLs can cause issues NULLs are safe
Best for Small result sets Large outer tables
Readability "value in list" "matching row exists"

Correlated vs Non-Correlated

Non-Correlated
The inner query runs once, independently. It does not reference any column from the outer query. Typical with IN.
Correlated
The inner query runs once per outer row because it references outer columns. Typical with EXISTS.

The NOT Variants

Both operators have negated forms: NOT IN and NOT EXISTS. They exclude rows instead of including them.

NOT IN
Returns rows whose value is not found in the subquery list. Beware: if the list contains NULL, the entire result can be empty!
NOT EXISTS
Returns rows where no matching row is found. Safe with NULLs and generally preferred for exclusion logic.

How to Write a Subquery

1
Identify the filter condition. What dynamic value or set of values do you need?
2
Write the inner query first. Run it alone to verify it returns the expected result.
3
Choose IN or EXISTS. Use IN for a value list, EXISTS for row-existence checks.
4
Wrap in parentheses and place after the WHERE keyword (or NOT IN / NOT EXISTS).
5
Test the full query. Check edge cases like empty subquery results and NULLs.

Example 1: Students Above Average

Goal: Find all students whose grade is higher than the class average.

SELECT name, grade FROM students WHERE grade \( > \) ( SELECT AVG(grade) FROM students );

Example 2: Products in Active Categories

Goal: List products that belong to categories marked as active.

SELECT product_name, price FROM products WHERE category_id IN ( SELECT id FROM categories WHERE status = 'active' );

Example 3: Customers with Orders

Goal: Find customers who have placed at least one order this year.

SELECT name, email FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.order_date \( \geq \) '2024-01-01' );

How EXISTS Executes

customers id name 1 Alice 2 Bob 3 Carol 4 Dave orders id customer_id order_date 101 1 2024-03 102 1 2024-06 103 3 2024-01 ✓ ✕ ✓ ✕ Result name Alice Carol

Common Mistakes to Avoid

✕ NULL in NOT IN
If the subquery returns any NULL, NOT IN returns zero rows. Use NOT EXISTS or filter NULLs out.
✕ Multi-Column with IN
IN expects the subquery to return exactly one column. Selecting multiple columns causes an error.
✕ Missing Correlation
Using EXISTS without linking inner and outer queries returns TRUE for every row, making the filter useless.

Summary Cheat Sheet

Pattern Syntax Use When
Scalar subquery WHERE col \( > \) (SELECT ...) Comparing to one value
IN subquery WHERE col IN (SELECT ...) Matching a list of values
NOT IN WHERE col NOT IN (SELECT ...) Excluding a list (no NULLs!)
EXISTS WHERE EXISTS (SELECT ...) Row-existence check
NOT EXISTS WHERE NOT EXISTS (SELECT ...) Safe exclusion pattern

Question 1 of 5

Which SQL keyword checks whether a subquery returns at least one row?

Question 2 of 5

What happens when a NOT IN subquery returns a NULL value in its result set?

Question 3 of 5

Which query correctly finds teachers with no awards?

Question 4 of 5

In a correlated subquery, how many times does the inner query execute?

Question 5 of 5

What type of subquery is this, and why?