← All Exercises

SQL Common Table Expressions

intermediatesql~20min

Background

CTEs (Common Table Expressions) create temporary named result sets, improving query readability and modularity.

Problem

Write a SQL query using a CTE to find departments with more than 5 employees and their average salary.

Input

An employees table with id, name, department, salary columns.

Output

Departments with >5 employees and their average salary.

Sample tests

Sample 1

Input: departments with 3, 7, and 10 employees
Expected: 2 departments (7 and 10 employees) with avg salary

Your solution

Learning objective

Learn CTE syntax, query decomposition, and the readability benefits over nested subqueries.