In PostgreSQL to repeat a string column value to a specified number of times we will be using the repeat() function. The repeat() function takes a string and a number as arguments and returns the string repeated that number of times.
Syntax of REPEAT() function in PostgreSQL:
REPEAT(string, number_of_times)
- string: The string to be repeated.
- number_of_times: The number of times the string should be repeated.
Examples
Example 1: Repeating a Specific String in PostgreSQL
To repeat the string ‘PostgreSQL’ 3 times:
SELECT REPEAT('PostgreSQL', 3) AS repeated_string;
Output:
Example 2: Repeating a Column in PostgreSQL:
We will be using Zipcodes table.
In order to repeat the column value in PostgreSQL we use repeat function along with the number of times to be repeated.
select *,REPEAT(state,3) as Repeat_States FROM zipcodes
Repeat function of state column repeats the column value 3 times so the resultant table will be
Output:
Example 3: Repeating Numeric (integer) a Column in PostgreSQL:
In order to repeat the numeric column in PostgreSQL we use repeat function along with the Typest to Text (:: Text) and the number of times to be repeated.
select *,REPEAT(zip::text,2) as repeat_zip FROM zipcodes
Repeat() function along with typecast will repeat the “zip” column value 2 times so the resultant table will be
Output: