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 basic syntax of a REPEAT is as follows:
SELECT REPEAT(string_name, count);
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:
Now, navigate to
http://localhost:8081/ to access phpMyAdmin. Then log in with the username
root and pass
Click the SQL tab and you are ready to go.
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;
|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.
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;
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;