SQL REPLICATE() function repeats a string value a specified number of times.


REPLICATE (inputstring, integer)

inputstring is the string of a character string or binary data type. It can be either a character or binary data.

integer is an any integer value, including bigint. If it is negative then NULL value is returned.

Lets look at an example of REPLICATE() function in SQL.

Using Replicate function with string

The following example uses REPLICATE() function and repates a given string for five time .

DECLARE @inputsrtring VARCHAR(100)='welcome to sqlskull.com ! '

SELECT REPLICATE(@inputsrtring,5) AS String_After_Replicate

Using Replicate function with character

The following example replicates a character for five time .

DECLARE @inputChar VARCHAR(5)= 'S'

SELECT REPLICATE(@inputChar,5) AS After_Replicate

Using a Replicate function for Generating a hint pattern (overriding a string charactes with any specific character)

You can override a string character with any specific character using replicate() function.

Usually, you may have come accross with a hint pattern most of the time during a password recovery OTP or any security page on bank websites wherein users are asked to choose either phone number or mail id for receiving an OTP while few of characters of phone number or mail id are hidden on page, especially characters are replaced with a  ‘*’ ,  which may be somthing like “Your OTP for password recovery is sent on this mail xyz*****@gmail.com”

Obviously, it is done for secuirty reasons,  just to give a quicky hint to user that you have to check that spceific mail id or phone number on which OTP is being sent without showing a complete mailid or phone number details on screen.

Following statement uses replicate function which adds five * in place of last five characters of phone number.

SELECT  PhoneNumber ,
SUBSTRING (PhoneNumber ,1,(LEN(PhoneNumber)-5 ) ) + REPLICATE('*',5) 
AS PhoneNumber_AfterReplicate  
FROM [Person].[PersonPhone]


As you can see, Last five characters are replicated with ‘*’,  It gives a hint that password is being sent on that phone number without displaying complete phone number .

Here we have used substring() function and len() function to get the substring from a string after excluding last five character of its length .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.