Recursive CTEs
12.23.2024
We’re thrilled to announce that recursive CTEs are now stable in Materialize! This milestone unlocks an entirely new class of iterative SQL queries, enabling you to work with hierarchical and recursive data structures directly in SQL.
Recursive CTEs are indispensable for applications requiring traversal or accumulation along hierarchical data - think organizational structures, bill of materials, or nested permissions. They make it possible to compute dynamic, incremental results in scenarios where standard SQL falls short.
But we didn’t stop at just implementing the standard WITH RECURSIVE clause. Instead, we took it a step further by supporting mutual recursion, a more powerful and expressive primitive that handles some of the fundamental limitations of traditional recursive CTEs.
Why mutual recursion?
The standard WITH RECURSIVE clause has practical issues when handling more complex computations or when multiple recursive relations depend on each other. By introducing the extended WITH MUTUALLY RECURSIVE clause, Materialize allows you to define interdependent recursive queries, opening the door to advanced use cases like:
- Stable matching algorithms;
- Dynamic programming for optimization problems;
- Solving all of 2023’s Advent of Code challenges;
- And much more - it’s Turing complete!
Example: permissions in hierarchical systems
One common use case for recursion in applications is resolving permissions in hierarchical systems. Think of scenarios like managing access for teams and sub-teams or sharing files within nested groups — permissions often need to flow from parent to child unless explicitly overridden. Using recursion, you can dynamically keep permissions up-to-date as the hierarchy structure changes.
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 | |
Ready to dive in? For more details on how Recursive CTEs work in Materialize, check out this blog post. If you have questions about the implementation or are curious if recursive CTEs can solve your use case, ping us on Slack!