Prepin
Log in

M

Create SQL code to generate the Fibonacci series.

Approach / Explanation

This question requests you to create SQL code that produces a sequence known as the Fibonacci series. In this series, each number following the initial two is the sum of the two preceding numbers, usually starting with 0 and 1. The interviewer aims to evaluate your capability to write SQL for intricate calculations and your understanding of recursive functions (functions that invoke themselves). Guidance: For operations like this in SQL, consider utilizing a recursive common table expression (CTE). The recursive section of the query should compute the next Fibonacci number by adding the current Fibonacci number to the one before it. Keep in mind that SQL does not support loops as other programming languages do, so constructs like while-loops or for-loops won't be applicable here.

Suggested Answer

By utilizing a recursive common table expression (CTE), you can create a Fibonacci series as demonstrated below: WITH RECURSIVE Fibonacci_Sequence (n, Fn, Fnext) AS ( SELECT 0, 0, 1 --Initial Row UNION ALL SELECT n+1, Fnext, Fn+Fnext -- Recursive CTE section FROM Fibonacci_Sequence WHERE n < 10 --Termination Condition ) SELECT n, Fn AS 'Fibonacci Number' FROM Fibonacci_Sequence; In the above code, the CTE contains three columns: "n" (for tracking the iterations), "Fn" (for the current Fibonacci number), and "Fnext" (for the subsequent Fibonacci number). The series begins with the initial values of n=0, Fn=0, and Fnext=1. During the recursive phase, for each new entry, "n" is increased, "Fn" is updated to reflect the next Fibonacci number, and "Fnext" is computed as the sum of the current Fibonacci number and the next. The output is the Fibonacci sequence up to the 10th term.

Alternative Answer

Here is another example with some variations: WITH RECURSIVE Fibonacci_Sequence (n, Fn) AS ( SELECT 1, 0 -- Base Case Row 1 UNION ALL SELECT 2, 1 -- Base Case Row 2 UNION ALL SELECT n+1, (SELECT sum(Fn) FROM Fibonacci_Sequence ORDER BY n DESC LIMIT 2) -- Recursive segment of the CTE FROM Fibonacci_Sequence WHERE n < 10 -- Termination Condition ) SELECT n, Fn AS 'Fibonacci Number' FROM Fibonacci_Sequence; This code adheres to the same principles but divides the base case into two seed rows for n=1 and n=2 along with their respective Fibonacci values. The recursive segment calculates the sum of the two most recently added Fibonacci numbers, thereby creating the next Fibonacci number. The new sequence number "n" is derived by incrementing the current "n". The result is the Fibonacci sequence up to 10.

Question Details

Difficulty & Category

Medium
sql

Companies

Google
Microsoft

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.