← Back to SQL, page 5

sql-0093 · Medium mid

Write a query for employees who earn more than the average of their own department. Explain how a correlated subquery is evaluated.

A correlated subquery refers to a column of the outer row: WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id). Logically it is re-evaluated for each outer row with that row's department. Optimizers may cache results per department or rewrite it as a join to a grouped table, but the result is the same.

Full answer

"Their own department" changes from row to row, so the subquery must know which row it is serving. It does that by referring to the outer alias e.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
                  FROM employees x
                  WHERE x.dept_id = e.dept_id)
ORDER BY e.dept_id, e.name;
namedept_idsalary
Asha1120000
Tom270000
Diego355000

Logically, for Asha the subquery computes the Engineering average (103333.33) and compares; for Tom it computes the Sales average (66000); and so on. That per-row dependency is what "correlated" means.

The same result as a join to a grouped derived table, which computes each department average once:

sql
SELECT e.name, e.dept_id, e.salary
FROM employees e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal
      FROM employees GROUP BY dept_id) d ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal
ORDER BY e.dept_id, e.name;
namedept_idsalary
Asha1120000
Tom270000
Diego355000

Which is faster depends on the engine and the data. SQLite shows the correlated version in its plan explicitly:

sql
EXPLAIN QUERY PLAN
SELECT e.name FROM employees e
WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id);
text
QUERY PLAN
SCAN e
CORRELATED SCALAR SUBQUERY 1
  SCAN x

PostgreSQL often decorrelates or caches such subqueries. A window function gives a third version that reads the table once: AVG(salary) OVER (PARTITION BY dept_id). In an interview, show the correlated form because it reads like the question, then mention the alternatives.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
                  FROM employees x
                  WHERE x.dept_id = e.dept_id)
ORDER BY e.dept_id, e.name;

SELECT e.name, e.dept_id, e.salary
FROM employees e
JOIN (SELECT dept_id, AVG(salary) AS avg_sal
      FROM employees GROUP BY dept_id) d ON d.dept_id = e.dept_id
WHERE e.salary > d.avg_sal
ORDER BY e.dept_id, e.name;

EXPLAIN QUERY PLAN
SELECT e.name FROM employees e
WHERE e.salary > (SELECT AVG(x.salary) FROM employees x WHERE x.dept_id = e.dept_id);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A correlated subquery references the outer row
  • Logically evaluated once per outer row
  • Equivalent to a join with a grouped derived table
  • A window function version reads the table once

Common mistakes

  • Forgetting the correlation condition and comparing with the company average
  • Using the same alias inside and outside so the correlation silently disappears

Follow-ups

  • Rewrite this with a window function.
  • Why might a correlated subquery be slow on a large table without an index?

Tips

  • Name the outer alias in the subquery explicitly; it shows where the correlation is