Sub topic 6
Correlated subqueries: referencing the outer row
This chapter assumes you know SELECT, WHERE, ORDER BY, aggregate functions, GROUP BY, INNER JOIN, LEFT JOIN, NULL, and three-valued logic. A correlated subquery is a subquery that refers to a column from the surrounding, or outer, query. The database evaluates that inner query in the context of each candidate outer row.
The working model
A regular subquery can run independently:
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The inner query returns one company-wide average. The outer query compares every employee with that same value.
A correlated subquery cannot run independently because it uses a value from the outer query. Consider finding employees who earn more than the average salary in their own department:
SELECT e.name, e.department_id, e.salary
FROM employees AS e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees AS e2
WHERE e2.department_id = e.department_id
);The aliases identify the two roles:
erepresents the employee currently being tested by the outer query.e2represents rows searched by the inner query.e.department_idconnects the inner query to the current outer row.
Conceptually, the database performs these steps:
- Choose an outer employee.
- Find employees in that employee's department.
- Calculate that department's average salary.
- Compare the outer employee's salary with the average.
- Keep or reject the outer row.
- Repeat for other employees.
The database optimizer may transform this process internally. The conceptual model helps you check whether the query expresses the intended relationship.
Correlated subqueries in the SELECT list
A correlated subquery can also calculate a value for each returned row. This example counts orders for every customer:
SELECT c.name,
(
SELECT COUNT(*)
FROM orders AS o
WHERE o.customer_id = c.id
) AS order_count
FROM customers AS c;The inner query returns one count for each customer. COUNT(*) returns zero when a customer has no matching orders, so the customer still appears in the result.
A scalar correlated subquery must return at most one value for each outer row. An aggregate such as COUNT or MAX naturally produces one value. Without an aggregate or another restriction, multiple matching rows can cause a “subquery returned more than one row” error.
Common errors and alternatives
A missing correlation condition changes the question. If the inner query does not contain a condition such as e2.department_id = e.department_id, it may calculate one global value instead of one value per department.
A correlated query can often be rewritten as a join. The join makes the grouped intermediate result explicit:
SELECT e.name, e.department_id, e.salary, da.avg_salary
FROM employees AS e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS da
ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;The correlated form can be clearer when the question is naturally phrased as “for this row, find related rows.” The join form can be easier to extend when you need several columns from the grouped result. Compare both with your database's query plan when the tables are large.
Exercise
How would you change the department-average query so it returns employees whose salary is equal to or greater than their department average?
Show answer
Change the comparison from > to >=: WHERE e.salary >= (SELECT AVG(e2.salary) FROM employees AS e2 WHERE e2.department_id = e.department_id).