Get Started

How to query the factorial of 6 recursively

In the last exercise, you queried the factorial 5! with an iterative solution. Now, you will calculate 6! recursively. We reduce the problem into smaller problems of the same type to define the factorial n! recursively. For this the following definition can be used:

  • 0! = 1 for step = 0
  • (n+1)! = n! * (step+1) for step > 0

With this simple definition you can calculate the factorial of every number. In this exercise, n! is represented by factorial.

You are going to leverage the definition above with the help of a recursive CTE.

This is a part of the course

“Hierarchical and Recursive Queries in SQL Server”

View Course

Exercise instructions

  • Initialize the fields factorial and step to 1.
  • Calculate the recursive part with factorial * (step + 1).
  • Stop the recursion process when the current iteration value is smaller than the target factorial number.

Hands-on interactive exercise

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

WITH calculate_factorial AS (
	SELECT 
		-- Initialize step and the factorial number      
      	___ AS step,
        ___ AS factorial
	UNION ALL
	SELECT 
	 	step + 1,
		-- Calculate the recursive part by n!*(n+1)
	    ___ * (step + 1)
	FROM calculate_factorial        
	-- Stop the recursion reaching the wanted factorial number
	WHERE step < ___)
    
SELECT factorial 
FROM calculate_factorial;
Edit and Run Code

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 5Exercise 8: How to query the factorial of 6 recursively
Exercise 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