AdvancedLesson 11 of 15
CTEs & Recursive Queries – SQL
Structuring complex queries with WITH, generating hierarchies and number sequences.
A CTE (Common Table Expression, WITH) gives a subquery a name and makes long statements readable – like a local helper variable for tables. Multiple CTEs are separated by commas and can build on each other.
WITH bestellwert AS (
SELECT bp.bestellung_id, SUM(bp.menge * p.preis) AS wert
FROM bestellpositionen bp
JOIN produkte p ON p.id = bp.produkt_id
GROUP BY bp.bestellung_id
),
kundenumsatz AS (
SELECT b.kunde_id, SUM(w.wert) AS umsatz
FROM bestellungen b JOIN bestellwert w ON w.bestellung_id = b.id
WHERE b.status <> 'storniert'
GROUP BY b.kunde_id
)
SELECT k.name, u.umsatz
FROM kundenumsatz u JOIN kunden k ON k.id = u.kunde_id
ORDER BY u.umsatz DESC; -- Ada 1138, Dana 1089, Ben 85 (Cem's order is cancelled)Recursive CTEs consist of an anchor part that starts things off and a recursive part that accesses the result so far, until nothing new is produced. Typical use cases: number/date sequences, category trees, bills of materials, org charts.
-- Numbers 1 to 5 (PostgreSQL alternative: generate_series(1, 5))
WITH RECURSIVE zaehler(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM zaehler WHERE n < 5
)
SELECT n FROM zaehler;
-- Hierarchy: category with parent category
WITH RECURSIVE baum(id, name, eltern_id, pfad, tiefe) AS (
SELECT id, name, eltern_id, name, 0 FROM kategorien WHERE eltern_id IS NULL
UNION ALL
SELECT k.id, k.name, k.eltern_id, baum.pfad || ' > ' || k.name, baum.tiefe + 1
FROM kategorien k JOIN baum ON k.eltern_id = baum.id
)
SELECT pfad, tiefe FROM baum ORDER BY pfad;WarningRecursive CTEs need a termination criterion (
WHERE n < 5, a finite tree). If the data contains cycles, they run forever – store the path and check against it, or limit the depth. In MySQL/SQLite WITH RECURSIVE is enough; PostgreSQL also requires the keyword.TipPostgreSQL (from 12) inlines simple CTEs; with
WITH x AS MATERIALIZED (...) you force a one-time computation, with NOT MATERIALIZED you force inlining. CTEs are not a performance tool, though, but a readability tool.