SQL•Recursive CTEs
SQL Recursive Common Table Expressions (WITH RECURSIVE)
Learn how to generate number sequences and traverse hierarchical data using recursive CTEs.
Syntax
WITH RECURSIVE cte AS (base_query UNION ALL recursive_query) SELECT * FROM cte;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| WITH RECURSIVE | CTE | Enables self-referential recursive SQL queries. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
-- Generating a sequence of numbers from 1 to 5 using Recursive CTE
WITH RECURSIVE Countdown(n) AS (
-- Anchor member
SELECT 5
UNION ALL
-- Recursive member
SELECT n - 1 FROM Countdown WHERE n > 1
)
SELECT
n AS count_number,
'T-minus ' || n || '...' AS announcement
FROM Countdown;Expected Output:
count_number announcement ------------ ------------ 5 T-minus 5... 4 T-minus 4... 3 T-minus 3... 2 T-minus 2... 1 T-minus 1...
How It Works: Step-by-Step
- Lines 2-8: Defines anchor (5) and recursive step (n - 1) with termination condition n > 1.
- Lines 9-12: Queries resulting virtual table.
Key Concepts
- Recursive CTEs simulate while loops in SQL.
- Always ensure the recursive query has a terminating WHERE clause to avoid infinite loops.
Common Mistake: Omitting the termination WHERE clause in a recursive CTE
Without a termination condition, recursive CTEs run indefinitely until hitting recursion depth limits.
❌ Incorrect
SELECT n + 1 FROM cte; // Infinite recursion!
✅ Correct
SELECT n + 1 FROM cte WHERE n < 10;
Related SQL Tutorials & Compiler
SQL Relational Set Aggregation Methods vs Raw Cursor Loops Performance
Compare relational set-based aggregation techniques with slow row-by-row procedural cursor loops in SQL.
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL String Operations and Concatenation (|| and LIKE)
Search text patterns using LIKE (%, _) and concatenate strings with the || operator.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.