MySQL LPAD is an inbuilt function in MySQL. It pads a string with specified characters on the left up to a given length. In this article, we will discuss the MySQL LPAD Function. Also, we will discuss a few examples of using it.
You can also read about MySQL RPAD Function.
LPAD (string, length, paddingString)
The MySQL LPAD Function expects three parameters. Moreover, all the parameters are mandatory.
- string: The first parameter specifies the original string.
- length: The second parameter specifies the length of the final string.
- If the length is smaller than the original length of the string, then the function removes the extra characters.
- If the length is greater than the original length of the string, the function pads the padding string from left.
- paddingString: The string to left pad the original string.
The MySQL LPAD returns a string after padding it with the specified string up to the given length from the left.
Let’s discuss a few examples of using the function.
Example 1: Length is Greater than Original Length
mysql> SELECT LPAD("Concatly", 15, "ABC") as paddedString; +-----------------+ | paddedString | +-----------------+ | ABCABCAConcatly | +-----------------+
In the above example, the function pads “ABC” from left of the original string to make a total of 15 characters.
Example 2: Length is Smaller than Original Length
Alternatively, if the length is smaller than the original length of the string, the function removes the extra characters.
mysql> SELECT LPAD("Concatly", 3, "ABC") as paddedString; +--------------+ | paddedString | +--------------+ | Con | +--------------+
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.