Last updated: December 2, 2026.
Use a correlated subquery to compute the average for the current row’s group. It can compare an employee’s salary with their department average without an explicit join.
SELECT e.employee_id, e.department_id, e.salary
FROM employees AS e
WHERE e.salary > (
SELECT AVG(peer.salary)
FROM employees AS peer
WHERE peer.department_id = e.department_id
)
ORDER BY e.employee_id;Define the comparison group
The inner query sees e.department_id from the outer row. As a result, AVG() uses salaries from that department, including the employee’s own salary. To compare with coworkers only, exclude the matching employee ID inside the subquery. For a department with only one employee, that version has no peer average and does not return the row.
AVG() ignores null salaries. A null outer salary or a null average does not satisfy the greater-than condition. With the ordinary equality predicate shown here, employees with no department also have no matching group. Decide how you want to treat unassigned employees before changing the comparison.
Inspect performance and preserve the intended population
Run EXPLAIN on MySQL and review how the inner query finds the matching department rows. An index beginning with department_id is a reasonable candidate to evaluate. Compare the plan and query time on representative data rather than assuming that the syntax alone determines performance.
MySQL also supports AVG(salary) OVER (PARTITION BY department_id) in a derived query. To filter on that result, apply the salary comparison in the outer query. Filters placed before window calculation change which rows count toward the average. Start with two departments of known salaries and one null value so you can verify both the grouping and the comparison.