Strings

RPAD

Pads a string on the right to the length you need.

Syntax

RPAD(<text>, <length>)
RPAD(<text>, <length>, <fill>)

Adds characters at the end until the string reaches the required length; without the third argument — spaces. Its mirror function is LPAD, which pads on the left. Often used to line text up in a column or pad a code to a fixed length.

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.

Pad on the right
SELECT RPAD('7', 4, '0') AS zeros,
RPAD('ab', 5, '.') AS dots;
zerosdots
7000ab...
Names and salaries in a column
SELECT RPAD(name, 8, '.') || salary AS line
FROM employees;
line
Emma....1200
Liam....1000
Olivia..1350
Noah....950
Sophia..1200

Each name is padded with dots to 8 characters, so the salaries line up neatly, like page numbers in a table of contents.

A longer string gets cut
SELECT RPAD('PostgreSQL', 4) AS cut;
cut
Post

Watch out

RPAD truncates a longer string rather than leaving it as is: RPAD('PostgreSQL', 4) gives Post.

It only accepts text: RPAD(1, 5, '0') throws function rpad(integer, integer, unknown) does not exist. Cast the type: RPAD(id::text, 5, '0').

Trailing spaces in the result aren't visible in the table, but they're there: RPAD('ab', 5) is ab plus three spaces.

Related functions