Medium Subqueries and CTEs Employees database

Use a CTE (WITH clause)

Question

Using a WITH clause, calculate the average salary of each department, then show the department name and its average (rounded) for departments whose average is above 6000.

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

nameavg_salary
Engineering8225
Sales6300

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

Hint

WITH name AS (SELECT ...) creates a named result you can join like a table.

Show the solution
solution.sql Run this code
WITH dept_avg AS (
  SELECT department_id, AVG(salary) AS avg_salary
  FROM employees
  GROUP BY department_id
)
SELECT d.name, ROUND(a.avg_salary) AS avg_salary
FROM dept_avg a
JOIN departments d ON d.id = a.department_id
WHERE a.avg_salary > 6000;

Why it works

The CTE dept_avg is calculated first and then used like a table in the main query. It splits a hard query into two easy steps that you can read from top to bottom.

Common mistake

A CTE only exists for the one statement that follows it. Running SELECT * FROM dept_avg on its own afterwards fails with "no such table".

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