Subqueries in
WHERE
Master the art of nesting queries inside WHERE clauses using IN and EXISTS to filter rows with powerful, dynamic conditions.
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
Why Subqueries Matter
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.
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.
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
The NOT Variants
Both operators have negated forms: NOT IN and NOT EXISTS. They exclude rows instead of including them.
How to Write a Subquery
Example 1: Students Above Average
Goal: Find all students whose grade is higher than the class average.
Example 2: Products in Active Categories
Goal: List products that belong to categories marked as active.
Example 3: Customers with Orders
Goal: Find customers who have placed at least one order this year.
How EXISTS Executes
Common Mistakes to Avoid
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
Given these two tables:
teachers (id, name, subject) and awards (id, teacher_id, year)
You want to find teachers who have never received an award.
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
Consider this query:
SELECT product_name FROM products WHERE category_id IN (SELECT id FROM categories WHERE status = 'active');
What type of subquery is this, and why?