Strings

LPAD

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

Syntax

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

Adds characters at the start until the string reaches the required length; without the third argument — spaces. Its mirror function is RPAD, which pads on the right. Most often used so that numbers have the same width: 7 → 0007.

Data for the examples

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

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

Leading zeros
SELECT LPAD('7', 4, '0') AS padded;
padded
0007
Order numbers of the same width
SELECT id,
LPAD(id::text, 5, '0') AS order_number
FROM orders;
idorder_number
100001
200002
300003
400004
500005

LPAD works with text, so we convert the number first: id::text.

A number with a prefix
SELECT id,
CONCAT('ORD-', LPAD(id::text, 5, '0')) AS order_code
FROM orders;
idorder_code
1ORD-00001
2ORD-00002
3ORD-00003
4ORD-00004
5ORD-00005

Watch out

LPAD truncates a longer string rather than leaving it as is: LPAD('12345', 3, '0') gives 123.

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

For numbers there's another way too: TO_CHAR(1, 'FM00000') gives 00001.

Related functions