Search This Blog

2023/04/18

How to generate Fibonacci sequence in Mysql



The Fibonacci sequence is a series of numbers

in which each number is the sum of the two

preceding numbers. The sequence starts with

0 and 1, and each subsequent number is the

sum of the previous two numbers.



Fibonacci sequence using CTE RECURSIVE:



WITH RECURSIVE fib(n, a, b) AS (

SELECT 1, 0, 1

UNION ALL

SELECT n+1, b, a+b FROM fib WHERE n<10

)

SELECT a FROM fib;

Output:

+------+

| a |

+------+

| 0 |

| 1 |

| 1 |

| 2 |

| 3 |

| 5 |

| 8 |

| 13 |

| 21 |

| 34 |

+------+


No comments:

Post a Comment