Skip to main content
Albero Academy

Common Table Expressions

Name a query with WITH to make complex logic readable.

Advanced Queries9 min

A CTE (Common Table Expression), written with WITH, names a query up front so the main query reads top to bottom. It's the cure for deeply nested subqueries — the same power, far more readable.

WITH

name a subquery
WITH prog_stats AS (
SELECT programme_id, AVG(package) AS avg_pkg, COUNT(*) AS n
FROM students
GROUP BY programme_id
)
SELECT p.name, ps.avg_pkg, ps.n
FROM prog_stats ps
JOIN programmes p ON p.id = ps.programme_id
WHERE ps.n >= 5
ORDER BY ps.avg_pkg DESC;

Recursive CTEs

walk a hierarchy
WITH RECURSIVE chain AS (
SELECT id, name, manager_id FROM employees WHERE id = 1 -- anchor
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e JOIN chain c ON e.manager_id = c.id -- recurse
)
SELECT * FROM chain;

Key takeaways

  1. 01A CTE (WITH name AS …) names a query so the main query reads top to bottom.
  2. 02It replaces deeply nested subqueries with readable named steps.
  3. 03You can define and chain several CTEs in one WITH.
  4. 04WITH RECURSIVE walks hierarchies and trees.

Finished this chapter?

Mark it complete to track your progress through SQL.