Deviopath › PostgreSQL

Above Their Department Average

Medium · Subqueries

A correlated subquery refers to the current row of the outer query, so it is evaluated again for every row: (SELECT AVG(salary) FROM employees e2 WHERE e2.department_id = e.department_id) is the average of the outer employee's own department.

Return name, department (the department's name) and salary of every employee who earns strictly more than the average salary of their department. Employees without a department are left out. Sort by department, then salary descending, then name.

Next: Latest Order per Customer