MySQL RPAD

The RPAD function in MySQL is used to pad a string with a specified number of characters on the right side. This function is particularly useful when you need to ensure that a string has a certain length by appending a specific character or a set of characters to the right.

Syntax

Here is the syntax for the RPAD function:

RPAD(str, length, padstr)

str: The input string that you want to pad.
length: The total length of the resulting string after padding.
padstr: The string or character to be added to the right of the input string to achieve the desired length.

Example

Now, let’s look at an example to better understand how to use the RPAD function:

SELECT RPAD('Hello', 10, '*') AS PaddedString;

In this example:

The input string is ‘Hello’.
The desired length is 10 characters.
The padding character is ‘*’.
The result of this query would be:

+--------------+
| PaddedString |
+--------------+
| Hello******  |
+--------------+

In this output, the original string ‘Hello’ is padded with ‘*’ characters on the right to make the total length 10 characters.

It’s important to note that if the length of the input string (str) combined with the padding characters exceeds the specified length (length), the excess characters will be truncated to match the desired length.

Here’s an example illustrating this scenario:

SELECT RPAD('Overflow', 5, '*') AS PaddedString;

In this case, the output will be:

+--------------+
| PaddedString |
+--------------+
| Overf        |
+--------------+

The input string ‘Overflow’ is padded with ‘*’ characters, but only the first 5 characters are retained to meet the specified length of 5.

In summary, the RPAD function in MySQL is a useful tool for padding strings on the right side to achieve a specific length, and it can be helpful in various scenarios where string manipulation is required.