Medium Subqueries and CTEs Employees database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

namesalary
Tom Becker8800
Ana Souza6500
Priya Nair9200
Lucas Moreau6800
Mei Chen7600
Hana Kim7300

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.