Strings

REPEAT

Repeats a string the given number of times.

Syntax

REPEAT(<text>, <times>)

Joins a string to itself: REPEAT('ab', 3) gives ababab. Handy for simple bar charts right in the query result, for separators or for masking: REPEAT('*', 4).

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Repeat a string
SELECT REPEAT('ab', 3) AS repeated,
REPEAT('-', 10) AS line;
repeatedline
ababab----------
A salary bar chart
SELECT name, salary,
REPEAT('█', salary / 100) AS bar
FROM employees;
namesalarybar
Emma1200████████████
Liam1000██████████
Olivia1350█████████████
Noah950█████████
Sophia1200████████████

One square is 100 of salary. Integer division drops the remainder, so the count comes out whole.

Hide a phone number except the last digits
SELECT name,
REPEAT('*', LENGTH(phone) - 3) || RIGHT(phone, 3) AS masked_phone
FROM employees;
namemasked_phone
Emma************123
LiamNULL
Olivia************456
Noah************789
SophiaNULL

Watch out

Zero or a negative count isn't an error but an empty string: REPEAT('ab', -1) gives ''.

The count must be an integer: REPEAT('*', salary / 100.0) throws function repeat(unknown, numeric) does not exist. Cast the type: (salary / 100.0)::int.

Related functions