How to print a triangle pattern in SQL

Anetshelani Maselesele
3 min readJul 17, 2021
https://dotnettutorials.net/lesson/right-triangle-star-pattern-csharp/

In this short article, I will take you guys through printing a basic triangle pattern in SQL. Before we start, remember that SQL syntax may differ depending on the Database Management System (DBMS) that you are using. We will use MS SQL Server syntax in this article.

This article was inspired by a question encountered in HackerRank, and is free for everyone, should you want to do more of SQL practices.

Now let’s get into the article. The question was:

P(R) represents a pattern drawn by Julia in R rows. The following pattern represent P(5):

https://dotnettutorials.net/lesson/right-triangle-star-pattern-csharp/

Write a query to print the pattern P(20).

I will call the asterisk a star for this article. Note that each star is separated from the one next to it by only one space.

STEP 1:

To solve this query, you first need to check how your pattern is designed. From the above picture, we can see that the first row has only one star, and they increase by one star as we move further down, up to 5 stars in the last row. Our question requires us to print a similar pattern, but with a maximum of 20 stars.

STEP 2:

Now let’s see how we can write the query to print P(20).

First we declare a variable using the DECLARE statement — you can name this variable whatever you want. I will name my variable ANE (the uppercase doesn’t really make a difference). But the variable needs to start with @ sign. So my variable will be @ANE. Then we define the datatype of our variable. Ours needs to be an integer because our pattern is being treated in numbers. We set our variable to 1 because our pattern starts with only one star in the first row. So:

DECLARE @ANE INT = 1

STEP 3:

We need to use a loop so that the query knows that it has to repeat the same pattern for as long as the condition is met. The loop need here is a WHILE loop, and we need the rows to be repeated 20 times. So our loop becomes:

WHILE @ANE <= 20

STEP 4:

MS SQL server requires that we tell it when to start and end printing the pattern, so we need the BEGIN and END statements.

Inside our statements, we need to tell the query what we want to print, and how long it should be. So we use a PRINT and REPLICATE command. We want to print our star, so we use ‘* ‘ and don’t forget to put the space after the star. And it needs to do this once. But we also need to tell it that whenever it replicates our star, it should increase each row by one star. So we need a SET command. In this case, a star, that should be incremented once in each row, starting from 1. So our complete query would be:

DECLARE @ANE INT = 1
WHILE @ANE <= 20
BEGIN
PRINT REPLICATE('* ', @ANE)
SET @ANE = @ANE + 1)
END

Congratulations! You have just printed your triangle using MS SQL server. I hope this article was helpful 💃.

--

--