Problems / Above-Average Earners / Editorial
A correlated subquery references a column from the outer query:
```sql
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department = e.department -- correlation
)
```
Conceptually, for each row in the outer query, the subquery runs with that row's department. In practice, the optimizer rewrites this as a hash join.
AVG("salary").over(Window.partitionBy("department")) computes the department average on every row. Then a simple filter(salary > department_avg) selects above-average earners.
AVG("salary").over(Window.partitionBy("department"))
filter(salary > department_avg)
JOIN (
SELECT department, AVG(salary) AS dept_avg
FROM employees GROUP BY department
) d ON e.department = d.department
WHERE e.salary > d.dept_avg
All three approaches produce identical results. The correlated subquery is the most educational for understanding row-level comparisons.
Solve Above-Average Earners yourself →