Created
July 25, 2021 12:08
-
-
Save Animesh-Ghosh/2d8313575868a45a76b824943dc7208d to your computer and use it in GitHub Desktop.
Recursive Common Table Expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- count till n | |
WITH RECURSIVE count_cte AS ( | |
SELECT 1 AS n -- anchor member | |
UNION | |
SELECT n + 1 -- recursive member | |
FROM count_cte WHERE n < 10 | |
) SELECT * FROM count_cte; | |
-- factorial | |
WITH RECURSIVE fact_cte AS ( | |
SELECT 1 AS n, 1 AS fact | |
UNION | |
SELECT n + 1, (n + 1) * fact | |
FROM fact_cte WHERE n < 10 | |
) SELECT * FROM fact_cte; | |
-- fibonacci | |
WITH RECURSIVE fib_cte AS ( | |
SELECT 1 AS n, 0 AS f1, 1 AS f2 | |
UNION | |
SELECT n + 1, f2 AS f1, f1 + f2 | |
FROM fib_cte WHERE n < 10 | |
) SELECT * FROM fib_cte; | |
-- multiplication | |
WITH RECURSIVE mul_cte AS ( | |
SELECT 5 AS a, 1 AS b, 5 AS c | |
UNION | |
SELECT a, b + 1, a * (b + 1) | |
FROM mul_cte WHERE b < 10 | |
) SELECT * FROM mul_cte; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment