In PostgreSQL, RPAD()
is a function that enables us to add padding to the right part of a string.
Syntax
The syntax goes like this:
rpad ( string text, length integer [, fill text ] )
Where:
string text
is the string to apply padding tolength integer
is the total length that you want the string to be after padding has been appliedfill text
is an optional argument that allows you to specify one or more characters to use as the padding (the default is a space).
Example
Here’s an example to demonstrate:
SELECT RPAD('Look', 8, '!');
Result:
Look!!!!
In this case, I padded the string with an exclamation mark. Seeing as I specified that the resulting string should be eight characters long, exclamation marks were replicated until they filled up the remaining part of the string.
Padding with Multiple Characters
The third argument can contain more than one character:
SELECT RPAD('Look', 13, ' at that!');
Result:
Look at that!
Bear in mind that it will still be repeated if it doesn’t use up all remaining space:
SELECT RPAD('Look', 23, ' at that!');
Result:
Look at that! at that!
Padding with Spaces
As mentioned, the last argument is optional, and the default padding character is a space.
Here’s an example of right padding a string with spaces:
SELECT CONCAT(RPAD('Look', 10), ' over there!');
Result:
Look over there!
In this case, I used the CONCAT()
function to concatenate our padded string with another string. I did this so that the padding effect is more visible.
This is the equivalent of doing the following:
SELECT CONCAT(RPAD('Look', 10, ' '), ' over there!');
Result:
Look over there!