Counting numbers recursively
In this first exercise, you will start with a math function to count numbers recursively. It is the series from 1
to target
and in this case your target
value is 50
.
This means the task is to count from 1
to 50
using a recursive query. The video showed you the pseudo-code version, and now it's your turn to write it in real code! You will have to define:
- The CTE with the definition of the initial and recursive query
- The appropriate termination condition for the recursion
This is a part of the course
“Hierarchical and Recursive Queries in SQL Server”
Exercise instructions
- Define the CTE with the name
counting_numbers
. - Initialize
number
in the initial query. - Add
1
tonumber
each recursion step. - Limit the recursion step to
50
in the recursive query.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
-- Define the CTE
___ ___ ___ (
SELECT
-- Initialize number
___ AS number
UNION ALL
SELECT
-- Increment number by 1
___
FROM counting_numbers
-- Set the termination condition
WHERE number < ___)
SELECT number
FROM counting_numbers;
This exercise is part of the course
Hierarchical and Recursive Queries in SQL Server
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 recursivelyExercise 9: Solve recursive maths problemsExercise 10: Counting numbers recursivelyExercise 11: Calculate the sum of potenciesWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.