Scalar subqueries in MySQL - Time & Space Complexity
When using scalar subqueries in SQL, it's important to understand how the query's running time changes as the data grows.
We want to know how many times the subquery runs and how that affects the total work done.
Analyze the time complexity of the following code snippet.
SELECT e.employee_id, e.name,
(SELECT d.department_name
FROM departments d
WHERE d.department_id = e.department_id) AS dept_name
FROM employees e;
This query selects each employee and uses a scalar subquery to find their department name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The scalar subquery runs once for each employee row.
- How many times: Equal to the number of employees (n).
As the number of employees grows, the subquery runs more times, increasing total work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 subquery executions |
| 100 | About 100 subquery executions |
| 1000 | About 1000 subquery executions |
Pattern observation: The total work grows directly with the number of employees.
Time Complexity: O(n)
This means the query's running time grows in a straight line as the number of employees increases.
[X] Wrong: "The scalar subquery runs only once regardless of employee count."
[OK] Correct: The subquery runs separately for each employee row, so its cost adds up with more employees.
Understanding how scalar subqueries affect performance helps you write efficient queries and explain your reasoning clearly in interviews.
What if we replaced the scalar subquery with a JOIN? How would the time complexity change?
Practice
Solution
Step 1: Understand scalar subquery definition
A scalar subquery returns exactly one value, not multiple rows or columns.Step 2: Identify usage in queries
This single value can be used inside another query, like in WHERE or SELECT clauses.Final Answer:
A single value that can be used in another query -> Option BQuick Check:
Scalar subquery = single value [OK]
- Thinking scalar subqueries return multiple rows
- Confusing scalar subqueries with table subqueries
- Assuming scalar subqueries return column names only
Solution
Step 1: Analyze correct scalar subquery syntax
The scalar subquery must be enclosed in parentheses and return a single value, as in (SELECT MAX(score) FROM scores).Step 2: Check placement in SELECT clause
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; correctly places the scalar subquery inside the SELECT list with an alias.Final Answer:
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; -> Option CQuick Check:
Scalar subquery syntax = SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; [OK]
- Missing parentheses around subquery
- Incorrect FROM clause placement
- Using aggregate functions without subquery
students(id, name)scores(student_id, score)What will this query return?
SELECT name, (SELECT AVG(score) FROM scores WHERE student_id = students.id) AS avg_score FROM students;
Solution
Step 1: Understand the subquery correlation
The subquery calculates the average score for each student by matching student_id with students.id.Step 2: Result of the main query
The main query returns each student's name along with their individual average score from the subquery.Final Answer:
Each student's name with their average score -> Option AQuick Check:
Scalar subquery returns per-student average [OK]
- Assuming subquery returns overall average for all rows
- Confusing correlated and uncorrelated subqueries
- Expecting syntax error when none exists
SELECT name, (SELECT score FROM scores) AS score FROM students;
Solution
Step 1: Analyze the subquery result
The subquery SELECT score FROM scores returns multiple rows because no WHERE clause limits it.Step 2: Understand scalar subquery requirement
Scalar subqueries must return exactly one value; multiple rows cause an error.Final Answer:
Subquery returns multiple rows causing an error -> Option DQuick Check:
Scalar subquery must return one value [OK]
- Ignoring multiple rows returned by subquery
- Assuming alias is mandatory for subquery
- Thinking query runs without error
Solution
Step 1: Understand the goal
We want students whose individual score is greater than the average score of all students.Step 2: Analyze each option
SELECT name FROM students WHERE score > (SELECT AVG(score) FROM scores); correctly compares each student's score with the average score using a scalar subquery.Final Answer:
SELECT name FROM students WHERE score > (SELECT AVG(score) FROM scores); -> Option AQuick Check:
Scalar subquery compares average with individual score [OK]
- Missing parentheses around subqueries
- Using subquery without correlation for individual scores
- Syntax errors from missing SELECT in WHERE
Ready to prove it?
Pass the test and this pattern moves unknown
