Get Started

Calculate the factorial of 5

An important mathematical operation is calculating the factorial of a positive integer n. The factorial of n is defined by the product of all positive integers less than or equal to n. For example, the factorial of 3 (denoted by n!) is defined as:

3! = 1 x 2 x 3 = 6

To calculate the factorial of n, many different solutions exist. In this exercise, you will determine the factorial of 5 iteratively with SQL. You can use DECLARE @local_variable to define variables in SQL Server.

Recall the syntax of a WHILE loop is:

WHILE condition
BEGIN
   {...statements...}
END;

This is a part of the course

“Hierarchical and Recursive Queries in SQL Server”

View Course

Exercise instructions

  • Set the @target factorial, which will also serve as the termination condition, to 5.
  • Initialize the @factorial result.
  • Calculate the @factorial number by taking the product of the factorial result so far and the current iteration.
  • Reduce the termination condition by 1 at the end of the iteration.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

-- Define the target factorial number
DECLARE @target float = ___
-- Initialization of the factorial result
DECLARE @factorial float = ___

WHILE @target > 0 
BEGIN
	-- Calculate the factorial number
	SET @factorial = @___ * @___
	-- Reduce the termination condition  
	SET @target = @___ - 1
END

SELECT @factorial;

This exercise is part of the course

Hierarchical and Recursive Queries in SQL Server

AdvancedSkill Level
2.0+
1 reviews

Learn how to write recursive queries and query hierarchical data structures.

In this chapter, you will learn about recursion and why it is beneficial to apply this technique. You will also refresh your knowledge about Common Expression Tables (CTE).

Exercise 1: Recap of Common Table Expressions (CTE)Exercise 2: What is a CTE?Exercise 3: A CTE for IT-positionsExercise 4: A CTE for high-paid IT-positionsExercise 5: Introduction to recursionExercise 6: Facts about recursionExercise 7: Calculate the factorial of 5
Exercise 8: How to query the factorial of 6 recursivelyExercise 9: Solve recursive maths problemsExercise 10: Counting numbers recursivelyExercise 11: Calculate the sum of potencies

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free