Lesson

MySQL RPAD() Function

10 min reading
Free Course

MySQL RPAD() Function

The RPAD() function appends padding characters to the right end of a string until it reaches an exact character width. Data engineers rely on it when generating fixed-width mainframe exports, aligned reports, and padded labels.

Syntax

RPAD(str, len, padstr)
  • str: The starting string or numeric value.
  • len: Target total length in characters.
  • padstr: String pattern repeated on the right side.
  • Return value: String of length len, or NULL on invalid or NULL arguments.

If padstr contains multiple characters, MySQL repeats the pattern and trims any leftover portion so the output stops precisely at len characters.

Practical Example

Suppose your warehouse scanner expects 10-character SKU labels padded with trailing dashes from demo_products. You also want to see what happens when a SKU is already wider than the target.

SELECT
    product_id,
    sku,
    RPAD(sku, 10, '-') AS fixed_sku,
    RPAD(product_name, 8, '.') AS short_label
FROM demo_products
ORDER BY product_id;
product_id sku fixed_sku short_label
1 KB-104 KB-104---- Mechanic
2 HUB-22 HUB-22---- USB-C Hu
3 PRO-9900-XL PRO-9900-X Laptop S

Notice row 3: 'PRO-9900-XL' is 11 characters long, so RPAD(sku, 10, '-') truncates the final 'L' to fit 10 characters!

Common Mistakes & NULL Behavior

  • Silent truncation of long strings: RPAD() never expands past len. If CHAR_LENGTH(str) > len, characters on the right are chopped off silently.
  • Empty padstr returns NULL when padding is needed: Calling RPAD('ABC', 6, '') returns NULL because an empty pattern cannot fill the remaining width.
  • Negative length returns NULL: Passing len < 0 evaluates to NULL.
  • NULL arguments: Any NULL in str, len, or padstr produces NULL.

Frequently Asked Questions

What happens if str is already the exact target length?

RPAD() returns str unchanged without appending any padding characters.

Can RPAD() add spaces for tabular alignment?

Yes. Passing ' ' as padstr right-pads text with spaces, though CHAR(n) columns or application formatting often handle column layout more cleanly.

Does RPAD() count characters or bytes?

It counts characters, so UTF-8 symbols like '€' count as 1 unit toward len.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum