Hard SubqueriesCTEs Premium

SQL interview question: Fibonacci With a Recursive CTE

Generate Fibonacci Sequence with SQL

Can you generate the Fibonacci sequence using only SQL? This is a fun brain teaser that tests recursive CTE mastery.

Generate the first 15 Fibonacci numbers using WITH RECURSIVE.

Return position (1-15) and fib_number. The sequence starts: 1, 1, 2, 3, 5, 8, 13...

Skills: recursive CTEs for computation (no tables needed)

Tables

departments 5 rows
  • id integer PK
  • name text
  • location text
idnamelocation
1EngineeringSan Francisco
2SalesNew York
3MarketingLos Angeles
employees 37 rows
  • id integer PK
  • first_name text
  • last_name text
  • email text
  • department_id integer → departments
  • salary integer
  • hire_date text
  • manager_id integer → employees
  • title text
idfirst_namelast_nameemaildepartment_idsalaryhire_datemanager_idtitle
1AliceChen[email protected]12500002015-01-15NULLCEO
2RobertMartinez[email protected]21800002016-03-20NULLCEO
3SarahJohnson[email protected]11500002017-06-101VP Engineering

Keep going