Working with REPEAT in MySQL

06.10.2022

Intro

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

The Syntax

The basic syntax of a REPEAT is as follows:

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

Getting Setup

We will be using docker in this article, but feel free to install your database locally instead. Once you have docker installed, create a new file called docker-compose.yml and add the following.

version: '3'
 
services:
  db:
    image: mysql:latest
    container_name: db
    environment:
      MYSQL_ROOT_PASSWORD: root_pass
      MYSQL_DATABASE: app_db
      MYSQL_USER: db_user
      MYSQL_PASSWORD: db_user_pass
    ports:
      - "6033:3306"
    volumes:
      - dbdata:/var/lib/mysql
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: pma
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      PMA_ARBITRARY: 1
    restart: always
    ports:
      - 8081:80

volumes:
  dbdata:

Next, run docker-compose up.

Now, navigate to http://localhost:8081/ to access phpMyAdmin. Then log in with the username root and pass root_pass.

Click the SQL tab and you are ready to go.

A Simple Example

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

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

That's the gist of using the REPEAT function. We can now move to a larger example of using REPEAT 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(
		REPEAT('x', 10 - len(first_name)),
		first_name
	) as username
from employees e;
username
xxxxxKeith
xxxxxxxJon
xxxxxxJane