Function Reference

LPAD

Pads a string on the left with another string up to the given length.

MySQL 8.1
LPAD(str, len, pad_str)

Parameters

strVARCHAR
Source string
lenINT
Length of the result in characters
pad_strVARCHAR
String used to pad str

Return value

A string of len characters; a longer str is cut on the right to len characters; NULL for a negative len; an empty string if pad_str is empty but padding is needed

Examples

Zeros on the left to a length

MySQL 8.1
SELECT LPAD('9', 5, '0');
LPAD('9', 5, '0')
00009

Cutting a long string

MySQL 8.1
SELECT LPAD('hello', 3, '*');
LPAD('hello', 3, '*')
hel

Product number with leading zeros

MySQL 8.1
SELECT LPAD(good_id, 4, '0') AS code,
	good_name
FROM Goods
LIMIT 5;
codegood_name
0001apartment fee
0002phone fee
0003bread
0004milk
0005red caviar

Details

If pad_str is longer than needed, only its beginning is used: LPAD('5', 4, 'ab') returns aba5. A number in str is converted to a string automatically, so LPAD(good_id, 4, '0') also works for a numeric column.

See also