How to use REPLICATE in Sql Server

06.08.2022

Intro

SQL Server provides the REPLICATE function to create a sequence of a string in repetition. For example, we can tell SQL Server to repeat the character 0 3 times to get 000. In this article, we will learn how to use the REPLICATE function in SQL Server.

The Syntax

The basic syntax of a REPLICATE is as follows:

SELECT REPLICATE(string_name, count);
  • string is the string to repeat
  • count is the number of times to repeat.

Getting Setup

For this, we will be using docker. This is recommended for more than just using SQL Server. To find how to install docker go here: https://docs.docker.com/engine/install/

Now create a file called docker-compose.yml and add the following.

version: "3.9"
services:
  db:
    image: "mcr.microsoft.com/mssql/server"
    ports: 
      - 1433:1433
    environment:
        SA_PASSWORD: "Your_password123"
        ACCEPT_EULA: "Y"

Open a terminal and go to the folder the file is located. Then run the following.

docker-compose up

If you are looking for another good reference, you can check here: https://docs.docker.com/samples/aspnet-mssql-compose/.

A Simple Example

The basic example is straight forward. We can run the REPLICATE function with a string and assign a number of times to replicate.

SELECT REPLICATE('Hello ', 6) as string;
string
Hello Hello Hello Hello Hello Hello

That's the gist of using the replicate function. We can now move to a larger example of using REPLICATE with a table. One common use case is to add padding with strings to align values in a table.

Creating a DB

We start by creating an employee table to work with.

CREATE TABLE employees (
    first_name VARCHAR (50) NOT NULL,
    last_name VARCHAR (50) NOT NULL
);

Next, we can insert some data.

insert into employees (first_name, last_name) 
	values 
	('Keith', 'Holliday'),
	('Jon', 'Doe'),
	('Jane', 'Doe');

And, we can preview the data like so.

SELECT * FROM employees;
first_name last_name
Keith Holliday
Jon Doe
Jane Doe

An Example

Now, we can select all the first names and add x as a padding to align all the values. This is common when marking products or building usernames that all require the same number of characters.

The count will be the number of characters we require, 10, minus the number of characters in the string.

select 
	CONCAT(
		REPLICATE('x', 10 - len(first_name)),
		first_name
	) as username
from employees e;
username
xxxxxKeith
xxxxxxxJon
xxxxxxJane