Bird
Raised Fist0
SQLquery~10 mins

Nested subqueries in SQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Nested subqueries
Start Outer Query
Encounter Subquery
Execute Subquery
Return Subquery Result
Use Result in Outer Query
Complete Outer Query Execution
The outer query pauses to run the inner subquery first, then uses its result to continue and finish.
Execution Sample
SQL
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales');
Find employees who work in the Sales department by first finding the Sales department's id.
Execution Table
StepActionQuery PartResult/Value
1Start outer querySELECT name FROM employees WHERE department_id = (...)Waiting for subquery result
2Execute subquerySELECT id FROM departments WHERE name = 'Sales'Returns id = 3
3Use subquery resultWHERE department_id = 3Filter employees with department_id = 3
4Fetch matching employeesSELECT name FROM employees WHERE department_id = 3Returns names: Alice, Bob
5End queryFull query executedResult set: ['Alice', 'Bob']
💡 Subquery returns department id 3, outer query uses it to filter employees, then finishes.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
subquery_resultNULL333
outer_filterNULLNULLdepartment_id = 3department_id = 3
result_setEmptyEmptyEmpty['Alice', 'Bob']
Key Moments - 2 Insights
Why does the outer query wait before filtering employees?
Because the outer query needs the subquery result first (see execution_table step 2) to know which department_id to filter by.
What happens if the subquery returns no rows?
The outer query's condition becomes false or NULL, so no employees match, resulting in an empty result set (not shown here but implied after step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value does the subquery return at step 2?
A3
BSales
CAlice
Ddepartment_id
💡 Hint
Check the 'Result/Value' column in step 2 of the execution_table.
At which step does the outer query apply the filter using the subquery result?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look for when 'WHERE department_id = 3' is used in the execution_table.
If the subquery returned id = 5 instead of 3, how would the final result set change?
AIt would include employees with department_id = 3
BIt would include employees with department_id = 5
CIt would return all employees
DIt would return no employees
💡 Hint
Refer to variable_tracker 'outer_filter' and how it uses the subquery_result.
Concept Snapshot
Nested subqueries run inside outer queries.
The subquery executes first and returns a value.
Outer query uses this value to filter or compare.
Syntax: SELECT ... WHERE column = (SELECT ...);
Useful to break complex queries into parts.
Full Transcript
Nested subqueries work by running the inner query first to get a value. Then the outer query uses that value to filter or find matching rows. For example, to find employees in the Sales department, the subquery finds the Sales department's id. The outer query then selects employees with that department id. The execution flow starts with the outer query, pauses to run the subquery, gets the result, and continues. Variables like subquery_result hold the inner query's output, which the outer query uses to filter data. If the subquery returns no rows, the outer query returns no results. This step-by-step process helps build complex queries in manageable parts.

Practice

(1/5)
1. What does a nested subquery in SQL do?
easy
A. Runs a query inside another query to filter or compare data
B. Creates a new table from existing data
C. Deletes data from multiple tables at once
D. Updates all rows in a table without conditions

Solution

  1. Step 1: Understand the concept of nested subqueries

    A nested subquery is a query inside another query that runs first to provide data for the outer query.
  2. Step 2: Identify the correct description

    Runs a query inside another query to filter or compare data correctly describes this behavior as running a query inside another to filter or compare data.
  3. Final Answer:

    Runs a query inside another query to filter or compare data -> Option A
  4. Quick Check:

    Nested subquery = query inside query [OK]
Hint: Nested means one query inside another [OK]
Common Mistakes:
  • Confusing nested subquery with table creation
  • Thinking nested subqueries delete data
  • Assuming nested subqueries update all rows blindly
2. Which of the following is the correct syntax for a nested subquery in SQL?
easy
A. SELECT * FROM table WHERE id IN SELECT id FROM table2 WHERE value = 10;
B. SELECT * FROM table WHERE id == (SELECT id FROM table2 WHERE value = 10);
C. SELECT * FROM table WHERE id = SELECT id FROM table2 WHERE value = 10;
D. SELECT * FROM table WHERE id = (SELECT id FROM table2 WHERE value = 10);

Solution

  1. Step 1: Review correct nested subquery syntax

    The inner query must be enclosed in parentheses and used with operators like = or IN.
  2. Step 2: Check each option

    SELECT * FROM table WHERE id = (SELECT id FROM table2 WHERE value = 10); uses parentheses correctly and equals operator, making it valid SQL syntax.
  3. Final Answer:

    SELECT * FROM table WHERE id = (SELECT id FROM table2 WHERE value = 10); -> Option D
  4. Quick Check:

    Nested subquery syntax uses parentheses [OK]
Hint: Always use parentheses around subqueries [OK]
Common Mistakes:
  • Missing parentheses around subquery
  • Using double equals (==) instead of single =
  • Omitting parentheses causing syntax errors
3. Given the tables:
Employees(emp_id, name, dept_id)
Departments(dept_id, dept_name)
What does this query return?
SELECT name FROM Employees WHERE dept_id = (SELECT dept_id FROM Departments WHERE dept_name = 'Sales');
medium
A. Names of employees who work in the Sales department
B. All employee names regardless of department
C. Department names where employees work
D. Employee names who do not work in Sales

Solution

  1. Step 1: Understand the inner query

    The inner query finds the dept_id for the 'Sales' department from Departments table.
  2. Step 2: Apply the outer query condition

    The outer query selects employee names whose dept_id matches the Sales dept_id found by the inner query.
  3. Final Answer:

    Names of employees who work in the Sales department -> Option A
  4. Quick Check:

    Inner query finds Sales dept_id, outer filters employees [OK]
Hint: Inner query finds filter value, outer applies it [OK]
Common Mistakes:
  • Thinking it returns all employees
  • Confusing employee names with department names
  • Assuming it returns employees not in Sales
4. Identify the error in this SQL query:
SELECT name FROM Employees WHERE dept_id = SELECT dept_id FROM Departments WHERE dept_name = 'HR';
medium
A. Using = instead of IN for subquery
B. Missing parentheses around the subquery
C. Wrong table name used in subquery
D. Subquery returns multiple columns

Solution

  1. Step 1: Check subquery syntax

    The subquery must be enclosed in parentheses to be valid inside WHERE clause.
  2. Step 2: Identify the missing parentheses

    The query lacks parentheses around the subquery, causing syntax error.
  3. Final Answer:

    Missing parentheses around the subquery -> Option B
  4. Quick Check:

    Subqueries need parentheses [OK]
Hint: Always wrap subqueries in parentheses [OK]
Common Mistakes:
  • Forgetting parentheses around subquery
  • Using wrong operator without parentheses
  • Assuming subquery syntax is optional
5. You want to find all customers who placed orders with amounts greater than the average order amount. Which query correctly uses a nested subquery to achieve this?
hard
A. SELECT customer_id FROM Orders WHERE amount < (SELECT AVG(amount) FROM Orders);
B. SELECT customer_id FROM Orders WHERE amount = (SELECT AVG(amount) FROM Orders);
C. SELECT customer_id FROM Orders WHERE amount > (SELECT AVG(amount) FROM Orders);
D. SELECT customer_id FROM Orders WHERE amount IN (SELECT AVG(amount) FROM Orders);

Solution

  1. Step 1: Understand the goal

    We want customers with orders greater than the average order amount.
  2. Step 2: Analyze each option's condition

    SELECT customer_id FROM Orders WHERE amount > (SELECT AVG(amount) FROM Orders); uses > with a subquery calculating average amount, correctly filtering orders above average.
  3. Final Answer:

    SELECT customer_id FROM Orders WHERE amount > (SELECT AVG(amount) FROM Orders); -> Option C
  4. Quick Check:

    Use > with AVG subquery to find above-average orders [OK]
Hint: Compare with (SELECT AVG(...)) using > for above average [OK]
Common Mistakes:
  • Using = instead of > to find above average
  • Using < which finds below average
  • Using IN with a single value subquery incorrectly