-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02.recursive-cte.sql
More file actions
104 lines (81 loc) · 2.83 KB
/
02.recursive-cte.sql
File metadata and controls
104 lines (81 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
-- =====================================================
-- Simple Bounded Counter (Very Light)
-- Demonstrates: Basic recursion structure
-- Resource impact: Minimal
-- =====================================================
WITH RECURSIVE counter AS (
-- Anchor
SELECT 1 AS n
UNION ALL
-- Recursive step (strictly bounded)
SELECT n + 1
FROM counter
WHERE n < 10)
SELECT *
FROM counter;
-- =====================================================
-- Generate Small Date Range
-- Demonstrates: Controlled time series
-- Resource impact: Small, bounded output
-- =====================================================
WITH RECURSIVE dates AS (SELECT DATE '2026-01-01' AS d
UNION ALL
SELECT (d + INTERVAL '1 day')::date
FROM dates
WHERE d < DATE '2026-01-07')
SELECT *
FROM dates;
-- =====================================================
-- Simple Region → Nation Traversal (Small Hierarchy)
-- Demonstrates: Hierarchical recursion
-- Resource impact: Very low (dataset small)
-- =====================================================
WITH RECURSIVE geo AS (
-- Anchor: Regions
SELECT r_regionkey AS id,
r_name AS name,
1 AS level
FROM region
UNION ALL
-- Recursive: Nations under each region
SELECT n.n_nationkey,
n.n_name,
geo.level + 1
FROM nation n
JOIN geo
ON n.n_regionkey = geo.id
WHERE geo.level = 1)
SELECT *
FROM geo
ORDER BY level, id;
-- =====================================================
-- Depth-Limited Recursion (Best Practice Pattern)
-- Demonstrates: Safety control using depth limit
-- Resource impact: Predictable and safe
-- =====================================================
WITH RECURSIVE numbered AS (SELECT 1 AS id, 1 AS depth
UNION ALL
SELECT id + 1, depth + 1
FROM numbered
WHERE depth < 3)
SELECT *
FROM numbered;
-- =====================================================
-- Controlled Hierarchy Count
-- Demonstrates: Measuring structure size
-- Resource impact: Very light
-- =====================================================
WITH RECURSIVE geo AS (SELECT r_regionkey AS id,
r_name AS name,
1 AS level
FROM region
UNION ALL
SELECT n.n_nationkey,
n.n_name,
geo.level + 1
FROM nation n
JOIN geo
ON n.n_regionkey = geo.id
WHERE geo.level = 1)
SELECT COUNT(*)
FROM geo;