Compare with an average using a subquery
Question
Show the name and salary of employees who earn more than the average salary of all employees.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name | salary |
|---|---|
| Tom Becker | 8800 |
| Ana Souza | 6500 |
| Priya Nair | 9200 |
| Lucas Moreau | 6800 |
| Mei Chen | 7600 |
| Hana Kim | 7300 |
Hint
Calculate the average in a subquery inside WHERE.
Show the solution
solution.sql
Run this code
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Why it works
The subquery in brackets runs first and returns one value, the average salary (about 6367). The outer query then compares each salary with that value.
Common mistake
WHERE salary > AVG(salary) does not work, because an aggregate cannot be used directly in WHERE. The subquery is what makes it possible.