Sub topic 10
CTEs as Named, Readable Subqueries
Assume you know SELECT, WHERE, GROUP BY, joins, aggregate functions, and NULL. A common table expression, or CTE, is a named query result that exists only while one SQL statement runs. You define a CTE with WITH, then use its name like a temporary table.
Why name a subquery?
A subquery in FROM can calculate an intermediate result:
SELECT d.name, s.avg_salary
FROM departments AS d
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS s
ON s.department_id = d.id;The query works, but the intermediate query has only the short alias s. A CTE gives that result a descriptive name and places the intermediate step before the main query:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT d.name, da.avg_salary
FROM departments AS d
JOIN dept_avg AS da
ON da.department_id = d.id;The CTE named dept_avg calculates one average per department. The main query joins those averages to departments.
Building a query in steps
A CTE is useful when a query has a clear sequence of operations. For example, first calculate each department's average salary, then find employees whose salary is above that average:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name,
e.department_id,
e.salary,
da.avg_salary
FROM employees AS e
JOIN dept_avg AS da
ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary
ORDER BY e.department_id, e.salary DESC;The database logically evaluates the CTE before using it in the main query. The CTE does not create a permanent table, and its name is unavailable after this statement finishes.
You can define several CTEs by separating them with commas. Later CTEs can use earlier ones:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
),
above_average AS (
SELECT name, department_id, salary
FROM employees AS e
JOIN dept_avg AS da
ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary
)
SELECT aa.name, d.name AS department_name, aa.salary
FROM above_average AS aa
JOIN departments AS d
ON d.id = aa.department_id;This structure separates calculation, filtering, and presentation. It can make errors easier to locate because each step has one purpose.
CTEs versus ordinary subqueries
Use an ordinary subquery when the logic is short and used once. Use a CTE when the intermediate result needs a meaningful name, contains several lines, or is referenced more than once. A CTE can also make a long statement easier to test: run the CTE's inner SELECT by itself before adding the main query.
CTE syntax is:
WITH name AS (
SELECT ...
)
SELECT ...
FROM name;Some database systems support WITH RECURSIVE for hierarchical data, such as an employee-management tree. That is a separate pattern. Ordinary CTEs do not repeatedly call themselves.
Exercise
Rewrite the following derived-table query as a CTE: SELECT x.departmentid, x.avgsalary FROM (SELECT departmentid, AVG(salary) AS avgsalary FROM employees GROUP BY department_id) AS x;
Show answer
WITH deptavg AS (SELECT departmentid, AVG(salary) AS avgsalary FROM employees GROUP BY departmentid) SELECT departmentid, avgsalary FROM dept_avg;