We can use PostgreSQL’s repeat()
function to repeat a string multiple times. We pass the string to the function, along with an integer that specifies how many times we want it repeated, and it returns the string repeated that many times.
Example
Here’s an example to demonstrate:
SELECT repeat('Go', 3);
Result:
GoGoGo
We can concatenate this with another string if required:
SELECT 'Just ' || repeat('Go', 3);
Result:
Just GoGoGo
And the count can be an expression like the following:
SELECT repeat('Go', 3 * 2);
Result:
GoGoGoGoGoGo
Passing a Null String
Passing a null value as the string results in null
being returned:
SELECT repeat(null, 3);
Result:
null
Passing a Null Count
Passing a null count results in null
being returned:
SELECT repeat('Go', null);
Result:
null
Passing a Negative Count
Passing a negative count value results in an empty string being returned:
SELECT repeat('Go', -3);
Result:
repeat
--------
(1 row)