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
WITH prog_stats AS (SELECT programme_id, AVG(package) AS avg_pkg, COUNT(*) AS nFROM studentsGROUP BY programme_id)SELECT p.name, ps.avg_pkg, ps.nFROM prog_stats psJOIN programmes p ON p.id = ps.programme_idWHERE ps.n >= 5ORDER BY ps.avg_pkg DESC;
Recursive CTEs
WITH RECURSIVE chain AS (SELECT id, name, manager_id FROM employees WHERE id = 1 -- anchorUNION ALLSELECT e.id, e.name, e.manager_idFROM employees e JOIN chain c ON e.manager_id = c.id -- recurse)SELECT * FROM chain;
Key takeaways
- 01A CTE (WITH name AS …) names a query so the main query reads top to bottom.
- 02It replaces deeply nested subqueries with readable named steps.
- 03You can define and chain several CTEs in one WITH.
- 04WITH RECURSIVE walks hierarchies and trees.
