Friday, December 20, 2024

MySQL RPAD() Function

 The RPAD() function in MySQL is used to pad the right side of a string with a specified character (or characters) to a given length. If the original string is already longer than the specified length, it is returned as-is. If the string is shorter than the specified length, it will be padded with the given character(s) until it reaches the desired length.

Syntax:

RPAD(string, length, pad_string)
  • string: The original string that you want to pad.
  • length: The total length of the string after padding.
  • pad_string: The string that will be used to pad the original string. This string is repeated if necessary.

Example Usage:

  1. Basic Example: Pad a string to a total length of 10 with spaces.

    SELECT RPAD('Hello', 10, ' ');
    

    Result: 'Hello ' (5 spaces added)

  2. Example with a Specific Character: Pad a string with the character *.

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

    Result: 'Hello*****' (5 asterisks added)

  3. Using a Multi-character Padding String:

    SELECT RPAD('Hello', 12, 'XYZ');
    

    Result: 'HelloXYZXYZ' (Repeated padding of XYZ to reach a length of 12)

  4. If the Original String is Longer:

    SELECT RPAD('Hello, World!', 10, '*');
    

    Result: 'Hello, World!' (No padding is added since the string length is already greater than 10)

This function is useful when formatting data, aligning text, or generating fixed-width strings for reports.

No comments:

Post a Comment