Why subqueries are needed in SQL - Performance Analysis
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time needed to run a query changes when it uses subqueries.
How does adding a subquery affect the work the database does?
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 = 'New York'
);
This query finds employees who work in departments located in New York using a subquery.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database first runs the subquery to find matching departments.
- How many times: The subquery runs once, then the main query checks each employee against the subquery results.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 employees, 3 departments | Runs subquery once (3 results), checks 10 employees |
| 100 employees, 10 departments | Runs subquery once (10 results), checks 100 employees |
| 1000 employees, 50 departments | Runs subquery once (50 results), checks 1000 employees |
Pattern observation: The subquery runs once, then the main query work grows with the number of employees.
Time Complexity: O(n + m)
This means the total work grows roughly with the size of both the subquery results and the main query rows.
[X] Wrong: "The subquery runs for every employee row."
[OK] Correct: The database usually runs the subquery once and reuses its results, so it does not repeat the subquery many times.
Understanding how subqueries affect query time helps you write clear and efficient database queries, a useful skill in many real projects.
"What if the subquery returned a very large list? How would that change the time complexity?"
Practice
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'NY');Solution
Step 1: Understand the role of subqueries
The subquery inside the IN clause fetches department IDs located in 'NY'.Step 2: See how the main query uses subquery results
The main query selects employees whose department_id matches those IDs from the subquery.Final Answer:
To use the result of one query inside another for filtering or comparison -> Option AQuick Check:
Subqueries help filter data using other query results [OK]
- Thinking subqueries speed up queries automatically
- Confusing subqueries with table creation
- Believing subqueries change database structure
Solution
Step 1: Check correct subquery syntax
Subqueries must be enclosed in parentheses and use a single equals sign for comparison.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.Final Answer:
SELECT name FROM employees WHERE id = (SELECT manager_id FROM departments WHERE id = 5); -> Option DQuick Check:
Subqueries need parentheses and single '=' [OK]
- Using '==' instead of '=' for comparison
- Forgetting parentheses around subqueries
- Using subqueries without proper syntax
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 | 3Solution
Step 1: Find department id for 'Sales'
The subquery returns id = 3 for 'Sales' department.Step 2: Select employees with department_id = 3
Employees Alice and Carol have department_id 3, so they are selected.Final Answer:
Alice and Carol -> Option CQuick Check:
Subquery returns 3, employees with department_id 3 selected [OK]
- Assuming subquery returns multiple rows causing error
- Selecting employees from wrong department
- Ignoring subquery result in main query
SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE location = 'LA';
Solution
Step 1: Check subquery syntax
The subquery must be enclosed in parentheses to be valid.Step 2: Confirm other parts
Using '=' is okay if subquery returns one value; table names are correct.Final Answer:
Missing parentheses around the subquery -> Option AQuick Check:
Subqueries need parentheses [OK]
- Forgetting parentheses around subqueries
- Assuming '=' works for multiple rows
- Misreading table names as errors
Solution
Step 1: Understand the goal
We want customers with orders greater than the average order amount.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.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.Final Answer:
SELECT customer_id FROM orders WHERE total_amount > (SELECT AVG(total_amount) FROM orders); -> Option BQuick Check:
Subquery calculates average, main query compares amounts [OK]
- Using aggregate functions without subqueries
- Misusing IN for single value comparisons
- Comparing with wrong operators or missing parentheses
