Why subqueries nest queries in MySQL - Performance Analysis
When we use subqueries in MySQL, one query runs inside another. This nesting can affect how long the database takes to get results.
We want to understand how the time to run the whole query changes as the data grows.
Analyze the time complexity of the following code snippet.
SELECT employee_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 by using a subquery inside the WHERE clause.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database scans the departments table to find matching department IDs, then scans the employees table to find matching employees.
- How many times: The subquery runs once, and its result is used to filter the employees table, which is scanned once.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 departments, 100 employees | Scan 10 departments + scan 100 employees |
| 100 departments, 1,000 employees | Scan 100 departments + scan 1,000 employees |
| 1,000 departments, 10,000 employees | Scan 1,000 departments + scan 10,000 employees |
Pattern observation: The total work grows roughly with the sum of the sizes of both tables scanned.
Time Complexity: O(m + n)
This means the time grows roughly in a straight line with the number of departments (m) plus the number of employees (n).
[X] Wrong: "The subquery runs once and does not affect the total time much."
[OK] Correct: Even though the subquery runs once, its result affects how many employees are checked, so both parts add up to the total time.
Understanding how nested queries affect performance helps you write better database queries and explain your thinking clearly in interviews.
What if the subquery returned a very large list of department IDs? 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 subquery usage
The inner querySELECT id FROM departments WHERE location = 'NY'finds department IDs in New York.Step 2: Use subquery results in outer query
The outer query selects employees whosedepartment_idmatches those IDs from the subquery.Final Answer:
To nest one query inside another and use its results -> Option AQuick Check:
Subqueries = nested queries using results [OK]
- Thinking subqueries change database structure
- Confusing subqueries with hardware upgrades
- Believing subqueries create tables automatically
Solution
Step 1: Check subquery syntax
Subqueries must be enclosed in parentheses and used with operators like = or IN.Step 2: Identify correct syntax
SELECT * FROM table1 WHERE id = (SELECT id FROM table2 WHERE condition); uses parentheses correctly and the = operator, which is valid syntax.Final Answer:
SELECT * FROM table1 WHERE id = (SELECT id FROM table2 WHERE condition); -> Option DQuick Check:
Subquery syntax requires parentheses [OK]
- Using double equals (==) instead of single equals (=)
- Omitting parentheses around subquery
- Using IN without parentheses
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'LA');
Given:
- departments table has ids 1,2,3 with locations NY, LA, LA respectively
- employees table has:
(name: Alice, department_id: 1),
(name: Bob, department_id: 2),
(name: Carol, department_id: 3),
(name: Dave, department_id: 4)
Solution
Step 1: Identify department IDs in LA
From departments, IDs with location 'LA' are 2 and 3.Step 2: Find employees in those departments
Employees with department_id 2 and 3 are Bob and Carol.Final Answer:
Bob, Carol -> Option AQuick Check:
Subquery filters departments = Bob, Carol [OK]
- Including employees from other departments
- Ignoring subquery filtering
- Assuming all employees are returned
SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE location = 'NY';
Solution
Step 1: Check subquery syntax
The subquery must be enclosed in parentheses to be valid.Step 2: Identify missing parentheses
The query lacks parentheses aroundSELECT id FROM departments WHERE location = 'NY'.Final Answer:
Missing parentheses around the subquery -> Option CQuick Check:
Subqueries need parentheses [OK]
- Forgetting parentheses causes syntax error
- Confusing = and IN without checking subquery results
- Assuming table names are incorrect without checking
Solution
Step 1: Understand the problem
We want employees earning more than their department's average salary.Step 2: Analyze subquery usage
SELECT name, salary FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); uses a correlated subquery that calculates average salary per employee's department.Step 3: Check other options
SELECT name, salary FROM employees WHERE salary > AVG(salary); lacks grouping, C compares salary to all salaries, D compares to all averages without correlation.Final Answer:
SELECT name, salary FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); -> Option BQuick Check:
Correlated subquery per department = SELECT name, salary FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); [OK]
- Using aggregate functions without grouping
- Not correlating subquery with outer query
- Comparing salary to unrelated values
Ready to prove it?
Pass the test and this pattern moves unknown
