Print different star patterns in SQL
Let’s see how we can print the pattern of various type using SQL.
Syntax :
Declare @variable_name DATATYPE -- first declare all the
-- variables with datatype
-- like (int)
select @variable = WITH_ANY_VALUE -- select the variable and
-- initialize with value
while CONDITION -- condition like @variable > 0
begin -- begin
print replicate('*', @variable) -- replicate insert the *
-- character in variable times
set increment/decrement -- in increment/decrement
-- @variable= @variable+1
END -- end while loop
First Pattern :
DECLARE @var int -- DeclareSELECT @var = 5 -- InitializationWHILE @var > 0 -- conditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var - 1 -- decrementEND -- END |
Output :
* * * * * * * * * * * * * * *
Second Pattern :
DECLARE @var int -- Declare SELECT @var = 1 -- initialization WHILE @var <= 5 -- ConditionBEGIN -- BeginPRINT replicate('* ', @var) -- PrintSET @var = @var + 1 -- SetEND -- end |
Output :
* * * * * * * * * * * * * * *
Third Pattern :
DECLARE @var int, @x int -- declare two variableSELECT @var = 4,@x = 1 -- initializationWHILE @x <=5 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var - 1 -- setset @x = @x + 1 -- setEND -- End |
Output :
*
**
***
****
*****
Fourth Pattern :
DECLARE @var int, @x int -- declare two variableSELECT @var = 0,@x = 5 -- initializationWHILE @x > 0 -- conditionBEGINPRINT space(@var) + replicate('*', @x) -- here space for -- create spaces SET @var = @var + 1 -- setset @x = @x - 1 -- setEND -- End |
Output :
*****
****
***
**
*
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.


