Nested subqueries in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using nested subqueries, it is important to understand how the work grows as the data gets bigger.
We want to know how many times the database repeats tasks inside these nested queries.
Analyze the time complexity of the following code snippet.
SELECT employee_id, name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location_id = 100
);
This query finds employees who work in departments located at a specific location.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner subquery scans the departments table once.
- How many times: The outer query scans the employees table once, then checks each employee's department against the subquery result.
As the number of employees and departments grows, the database does more work to match employees to departments.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 employees, 5 departments | About 10 checks against 5 departments |
| 100 employees, 50 departments | About 100 checks against 50 departments |
| 1000 employees, 500 departments | About 1000 checks against 500 departments |
Pattern observation: The work grows roughly by multiplying the number of employees by the number of departments.
Time Complexity: O(n * m)
This means the work grows by multiplying the size of the outer table by the size of the inner table.
[X] Wrong: "The inner subquery runs only once, so the time is just O(n)."
[OK] Correct: The inner subquery result is used for each row in the outer query, so the total work depends on both tables.
Understanding how nested subqueries affect performance helps you write better queries and explain your choices clearly.
"What if we replaced the IN subquery with a JOIN? How would the time complexity change?"
Practice
Solution
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.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.Final Answer:
Runs a query inside another query to filter or compare data -> Option AQuick Check:
Nested subquery = query inside query [OK]
- Confusing nested subquery with table creation
- Thinking nested subqueries delete data
- Assuming nested subqueries update all rows blindly
Solution
Step 1: Review correct nested subquery syntax
The inner query must be enclosed in parentheses and used with operators like = or IN.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.Final Answer:
SELECT * FROM table WHERE id = (SELECT id FROM table2 WHERE value = 10); -> Option DQuick Check:
Nested subquery syntax uses parentheses [OK]
- Missing parentheses around subquery
- Using double equals (==) instead of single =
- Omitting parentheses causing syntax errors
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');
Solution
Step 1: Understand the inner query
The inner query finds the dept_id for the 'Sales' department from Departments table.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.Final Answer:
Names of employees who work in the Sales department -> Option AQuick Check:
Inner query finds Sales dept_id, outer filters employees [OK]
- Thinking it returns all employees
- Confusing employee names with department names
- Assuming it returns employees not in Sales
SELECT name FROM Employees WHERE dept_id = SELECT dept_id FROM Departments WHERE dept_name = 'HR';
Solution
Step 1: Check subquery syntax
The subquery must be enclosed in parentheses to be valid inside WHERE clause.Step 2: Identify the missing parentheses
The query lacks parentheses around the subquery, causing syntax error.Final Answer:
Missing parentheses around the subquery -> Option BQuick Check:
Subqueries need parentheses [OK]
- Forgetting parentheses around subquery
- Using wrong operator without parentheses
- Assuming subquery syntax is optional
Solution
Step 1: Understand the goal
We want customers with orders greater than the average order amount.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.Final Answer:
SELECT customer_id FROM Orders WHERE amount > (SELECT AVG(amount) FROM Orders); -> Option CQuick Check:
Use > with AVG subquery to find above-average orders [OK]
- Using = instead of > to find above average
- Using < which finds below average
- Using IN with a single value subquery incorrectly
