Bird
Raised Fist0
SQLquery~10 mins

Why subqueries are needed in SQL - Visual Breakdown

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 - Why subqueries are needed
Start Query
Identify need for intermediate result
Write subquery to get intermediate data
Use subquery result in main query
Execute subquery first
Use subquery output in main query execution
Return final result
Subqueries let us get intermediate results inside a bigger query, so we can use those results to filter or calculate more complex answers.
Execution Sample
SQL
SELECT name
FROM employees
WHERE department_id = (
  SELECT id FROM departments WHERE name = 'Sales'
);
This query finds employees who work in the 'Sales' department by first finding the department's id using a subquery.
Execution Table
StepActionQuery PartResult/Value
1Start main querySELECT name FROM employees WHERE department_id = (subquery)No rows yet
2Execute subquerySELECT id FROM departments WHERE name = 'Sales'Returns id = 3
3Use subquery resultWHERE department_id = 3Filter employees with department_id = 3
4Retrieve matching employeesSELECT name FROM employees WHERE department_id = 3Returns names: Alice, Bob
5Return final resultFull query resultAlice, Bob
💡 Subquery executed first to get department id; then main query filters employees using that id.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
subquery_resultNone333
filtered_employeesNoneNoneAlice, BobAlice, Bob
Key Moments - 2 Insights
Why do we run the subquery before the main query filters employees?
Because the main query needs the department id from the subquery to know which employees to select, as shown in execution_table step 2 and 3.
Can we write this query without a subquery?
Not easily, because we need to find the department id dynamically based on the department name, which requires the subquery to get that intermediate value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the subquery result at step 2?
AAlice
B3
CSales
Ddepartment_id
💡 Hint
Check the 'Result/Value' column at step 2 in execution_table.
At which step does the main query filter employees using the subquery result?
AStep 3
BStep 5
CStep 1
DStep 2
💡 Hint
Look for the step where 'WHERE department_id = 3' is applied in execution_table.
If the subquery returned no rows, what would happen to the main query result?
AIt would return all employees
BIt would cause an error
CIt would return no employees
DIt would return employees from all departments except Sales
💡 Hint
Think about how filtering by a non-existent department_id affects the main query result.
Concept Snapshot
Subqueries let you run a query inside another query.
They help get intermediate results to use in the main query.
The subquery runs first, then its result filters or calculates in the main query.
Use subqueries to handle complex filtering or calculations that need data from another query.
Example: find employees in a department by first getting the department id with a subquery.
Full Transcript
Subqueries are needed when you want to use the result of one query inside another. For example, to find employees in the 'Sales' department, you first find the department's id with a subquery. This id is then used to filter employees in the main query. The subquery runs first and returns the department id. Then the main query uses that id to select employees. This process allows complex queries to be broken down into smaller steps, making them easier to write and understand. Without subqueries, you would struggle to get intermediate data needed for filtering or calculations inside a single query.

Practice

(1/5)
1. Why do we use subqueries in SQL?
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'NY');
easy
A. To use the result of one query inside another for filtering or comparison
B. To speed up the database server automatically
C. To create new tables from existing ones
D. To change the database schema

Solution

  1. Step 1: Understand the role of subqueries

    The subquery inside the IN clause fetches department IDs located in 'NY'.
  2. Step 2: See how the main query uses subquery results

    The main query selects employees whose department_id matches those IDs from the subquery.
  3. Final Answer:

    To use the result of one query inside another for filtering or comparison -> Option A
  4. Quick Check:

    Subqueries help filter data using other query results [OK]
Hint: Subqueries let queries talk to each other inside SQL [OK]
Common Mistakes:
  • Thinking subqueries speed up queries automatically
  • Confusing subqueries with table creation
  • Believing subqueries change database structure
2. Which of the following is the correct syntax for a subquery in SQL?
easy
A. SELECT name FROM employees WHERE id IN SELECT manager_id FROM departments WHERE id = 5;
B. SELECT name FROM employees WHERE id == (SELECT manager_id FROM departments WHERE id = 5);
C. SELECT name FROM employees WHERE id = SELECT manager_id FROM departments WHERE id = 5;
D. SELECT name FROM employees WHERE id = (SELECT manager_id FROM departments WHERE id = 5);

Solution

  1. Step 1: Check correct subquery syntax

    Subqueries must be enclosed in parentheses and use a single equals sign for comparison.
  2. Step 2: Identify syntax errors in other options

    SELECT name FROM employees WHERE id == (SELECT manager_id FROM departments WHERE id = 5); uses '==' which is invalid in SQL; C misses parentheses; D misses parentheses around subquery.
  3. Final Answer:

    SELECT name FROM employees WHERE id = (SELECT manager_id FROM departments WHERE id = 5); -> Option D
  4. Quick Check:

    Subqueries need parentheses and single '=' [OK]
Hint: Subqueries always go inside parentheses with '=' or IN [OK]
Common Mistakes:
  • Using '==' instead of '=' for comparison
  • Forgetting parentheses around subqueries
  • Using subqueries without proper syntax
3. What will be the output of this query?
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales');

Assuming the departments table has one row with name 'Sales' and id 3, and employees table has:
id | name | department_id
1 | Alice | 3
2 | Bob | 2
3 | Carol | 3
medium
A. No rows returned
B. Bob only
C. Alice and Carol
D. Alice, Bob, and Carol

Solution

  1. Step 1: Find department id for 'Sales'

    The subquery returns id = 3 for 'Sales' department.
  2. Step 2: Select employees with department_id = 3

    Employees Alice and Carol have department_id 3, so they are selected.
  3. Final Answer:

    Alice and Carol -> Option C
  4. Quick Check:

    Subquery returns 3, employees with department_id 3 selected [OK]
Hint: Match subquery result with main query filter [OK]
Common Mistakes:
  • Assuming subquery returns multiple rows causing error
  • Selecting employees from wrong department
  • Ignoring subquery result in main query
4. Identify the error in this SQL query:
SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE location = 'LA';
medium
A. Missing parentheses around the subquery
B. Using '=' instead of 'IN' for multiple results
C. Wrong table name 'employees'
D. No error, query is correct

Solution

  1. Step 1: Check subquery syntax

    The subquery must be enclosed in parentheses to be valid.
  2. Step 2: Confirm other parts

    Using '=' is okay if subquery returns one value; table names are correct.
  3. Final Answer:

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

    Subqueries need parentheses [OK]
Hint: Always put subqueries inside parentheses [OK]
Common Mistakes:
  • Forgetting parentheses around subqueries
  • Assuming '=' works for multiple rows
  • Misreading table names as errors
5. You want to find all customers who placed orders with a total amount greater than the average order amount. Which query correctly uses a subquery to achieve this?
hard
A. SELECT customer_id FROM orders WHERE total_amount > AVG(total_amount);
B. SELECT customer_id FROM orders WHERE total_amount > (SELECT AVG(total_amount) FROM orders);
C. SELECT customer_id FROM orders WHERE total_amount IN (SELECT AVG(total_amount) FROM orders);
D. SELECT customer_id FROM orders WHERE total_amount = (SELECT total_amount FROM orders WHERE total_amount > AVG(total_amount));

Solution

  1. Step 1: Understand the goal

    We want customers with orders greater than the average order amount.
  2. Step 2: Check subquery usage

    SELECT customer_id FROM orders WHERE total_amount > (SELECT AVG(total_amount) FROM orders); correctly uses a subquery to calculate average and compares each order's total_amount to it.
  3. Step 3: Identify errors in other options

    SELECT customer_id FROM orders WHERE total_amount > AVG(total_amount); misuses AVG without subquery; C uses IN incorrectly; D has wrong comparison logic.
  4. Final Answer:

    SELECT customer_id FROM orders WHERE total_amount > (SELECT AVG(total_amount) FROM orders); -> Option B
  5. Quick Check:

    Subquery calculates average, main query compares amounts [OK]
Hint: Use subquery to get average, compare in main query [OK]
Common Mistakes:
  • Using aggregate functions without subqueries
  • Misusing IN for single value comparisons
  • Comparing with wrong operators or missing parentheses