Fibonacci series using a recursive Common Table Expression (CTE) in SQL - AI HintsToday

Fibonacci series using a recursive Common Table Expression (CTE) in SQL

Home Forums SQL Discussion Fibonacci series using a recursive Common Table Expression (CTE) in SQL

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #288
    Team AHT
    Keymaster

      WITH RECURSIVE FibonacciCTE AS (
      SELECT
      0 AS n,
      0 AS fib_n,
      1 AS fib_n_plus_1
      UNION ALL
      SELECT
      n + 1,
      fib_n_plus_1,
      fib_n + fib_n_plus_1
      FROM FibonacciCTE
      WHERE n < 10 — Change the limit according to how many Fibonacci numbers you want
      )
      SELECT fib_n AS Fibonacci_Number
      FROM FibonacciCTE;

      This SQL query defines a recursive CTE named FibonacciCTE. It starts with two initial values: fib_n and fib_n_plus_1 set to 0 and 1 respectively, corresponding to the first two Fibonacci numbers. Then, it recursively generates the subsequent Fibonacci numbers by adding the current and previous Fibonacci numbers until reaching the desired limit (in this example, 10 Fibonacci numbers). Finally, the query selects the Fibonacci numbers from the CTE.

      You can adjust the WHERE clause condition (n < 10 in this example) to control how many Fibonacci numbers you want to generate.

    Viewing 1 post (of 1 total)
    • You must be logged in to reply to this topic.