Employees With No Direct Reports (Anti-Join)
HR wants to identify individual contributors -- employees nobody reports to. Using a correlated NOT EXISTS subquery...
Nest one query inside another when you need its answer first.
A subquery is a SELECT nested inside another statement, used when one query needs the answer to a smaller query first. A scalar subquery returns a single value and can sit in the SELECT list or a comparison, while a correlated subquery references the outer row and is re-evaluated for each of them. These questions build the judgement for when a subquery is the clearest tool and when a join or CTE would read better and run faster.
FAQ
Short answers to what people get stuck on most. Tap a question to expand it.
Both can often give the same result. Choose by readability and by which columns you need.
-- customers with at least one order
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);A correlated subquery references a column from the outer query, so it is logically re-evaluated for every outer row.
SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id
);If the subquery returns even one NULL, NOT IN returns no rows at all.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);Track your streak & earn XP
Sign up free to unlock your progress dashboard, daily streaks, and leaderboard ranking.
10 role-based tests for Data Analysts, SQL Developers & Data Engineers with instant scorecards.