Press "Enter" to skip to content

The Fibonacci Sequence and Factorials in T-SQL

Tomaz Kastrun has a new series running this month, and it’s all about mathematical operations in T-SQL. Day 1 kicks us off with the Fibonnaci sequence:

T-SQL is funny solving fibonacci sequence. It has been done so many times, that it is nothing new. Problems are two-fold. The bigint will be maxed out by 91st number and recursions must be controlled.

So in this case, I have put MAXRECURSION to a given number of 150, yet I am controlling the ā€œnā€ within the CTE.

Day 2 covers factorial numbers:

T-SQL is funny solving factorial numbers. As it exists in scripting and programming languages, there is still none available in T-SQL. The closes is a PRODUCT() function, but it is not factorial out-of-the-box. Similar to Fibonacci, Factorial also has similar problems The bigint will be maxed very fast, so using DECIMAL(38) will get you yo 34!

Click through for versions of the factorial query that work for SQL Server 2025 and for prior versions that did not have PRODUCT().

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.