MySQL RPAD() Function
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, orNULLon invalid orNULLarguments.
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 pastlen. IfCHAR_LENGTH(str) > len, characters on the right are chopped off silently. - Empty padstr returns NULL when padding is needed: Calling
RPAD('ABC', 6, '')returnsNULLbecause an empty pattern cannot fill the remaining width. - Negative length returns NULL: Passing
len < 0evaluates toNULL. - NULL arguments: Any
NULLinstr,len, orpadstrproducesNULL.
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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.