MySQL LPAD Function | Pad a String with Another String

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.

Syntax

LPAD (string, length, paddingString)

Parameters

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.

Return Value

The MySQL LPAD returns a string after padding it with the specified string up to the given length from the left.

MySQL Lpad Function

Examples

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          |
+--------------+

Conclusion

In conclusion, we discussed the MySQL LPAD Function. You can read more about it on the Official MySQL Documentation. Additionally, you can read about more MySQL String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *