MySQL RPAD() Function

The RPAD() function in MySQL adds a specified string to the right-hand side of an existing string until the combined string reaches a certain length. This is very useful for formatting strings to a consistent length or for padding strings with trailing characters.



RPAD(): Definition and Usage

RPAD() is used to right-pad strings, meaning it adds characters to the end of the string. This is often necessary for creating strings of a consistent length for things like formatting reports or aligning text. If the original string is already longer than the target length, the original string is truncated from the right to match the target length.

Syntax

Syntax

RPAD(string, length, pad_string)
      

Parameter Values

Parameter Description
string The original string. This is required.
length The desired final length of the string after padding. If the original string is longer, it's truncated from the right to this length. This is required.
pad_string The string used for padding (added to the right of the original string). This is required.

Related Function

For left-padding (adding characters to the beginning of a string), use the LPAD() function.

Examples

Padding a String Literal

This example right-pads the string "SQL Tutorial" with "ABC" until it reaches a length of 20 characters.

Syntax

SELECT RPAD("SQL Tutorial", 20, "ABC");
      
Output

SQL TutorialABCABCABC
      

Padding Strings from a Column

This example right-pads the 'CustomerName' column from the 'Customers' table with "ABC" to a total length of 30 characters (assuming a 'Customers' table exists with a 'CustomerName' column).

Syntax

SELECT RPAD(CustomerName, 30, "ABC") AS RightPadCustomerName
FROM Customers;
      
Output

RightPadCustomerName
---------------------
(Each CustomerName right-padded with "ABC" to a length of 30 characters)
      

**Note:** In the second example, the output will depend on the data in your `Customers` table. Each `CustomerName` will be padded to 30 characters using "ABC" added to the right. If a `CustomerName` is already longer than 30 characters, it will be truncated from the right to fit within the 30-character limit.