A query inside a query — watch the engine run the inner SELECT first and feed its answer to the outer one.
The big picture
A query inside a query
Some questions cannot be answered in one flat WHERE — like "who earns more than the average?". The answer needs two queries, and SQL lets you nest one inside the other.
1
Nested queries
A subquery is a complete SELECT wrapped in parentheses, living inside another statement.
2
Inner runs first
The engine evaluates the innermost query, then hands its result up to the outer query.
3
One value or a list
A scalar subquery returns a single value usable like a number; IN ( ... ) consumes a whole list of values.
4
Readable questions
Who earns above average? is awkward in one WHERE but natural as two small queries.
A query inside a query
Nested queries1A subquery is a complete SELECT wrapped in parentheses, living inside another statement.
Inner runs first2The engine evaluates the innermost query, then hands its result up to the outer query.
One value or a list3A scalar subquery returns a single value usable like a number; IN ( ... ) consumes a whole list of values.
Readable questions4Who earns above average? is awkward in one WHERE but natural as two small queries.
4 building blocks make up A query inside a query
Watch it run
The inner query always runs first
Press play: the engine dives into the parentheses, computes the average, then pastes the number into the outer WHERE.
avg_salary.sql
1-- Who earns more than the average salary?
2SELECT name, salary
3FROM employees
4WHERE salary >(
5SELECTAVG(salary)
6FROM employees
7);
The question: find everyone above the company average. The average is itself a query — so it lives in parentheses.
Memory
no variables yet — press play
Console
output appears as the program runs…
Step 1/13
How it works
How a subquery executes
Click each stage — the value travels from the inner query up into the outer one.
Practice
Match the subquery vocabulary
Click a term, then click its description to lock the pair.
5 conceptsTap a card to expand
?Subquerydrops into place
?Inner querydrops into place
?Scalar subquerydrops into place
?IN ( ... )drops into place
?Nestingdrops into place
Challenge
Predict the top earner query
The subquery finds a number first. What does the outer query return?
top_earner.sql
1-- employees has 6 rows
2SELECT name
3FROM employees
4WHERE salary =(
5SELECTMAX(salary)
6FROM employees
7);
Your predicted output — one line per console line
Hint: MAX runs first and finds 92000. The outer query then keeps the one name whose salary equals it.
Recap
Key takeaways
Key takeaways5 takeaways
01
The inner query runs first, all by itself.
02
Its result is pasted into the outer query as a value or a list.
03
A scalar subquery gives one value; IN ( ... ) takes a whole list.
04
Parentheses mark the boundary — the engine reads them before anything else.
05
If a question needs two steps, write two queries and nest them.