MySQL LPAD() Function
MySQL LPAD() Function
The LPAD() function adds padding characters to the left side of a string until the result reaches a target character length. Teams commonly use it to format zero-padded employee IDs, invoice numbers, and fixed-width export fields.
Syntax
LPAD(str, len, padstr)
- str: The original string or number (converted to string automatically).
- len: Target final length in characters.
- padstr: The character or pattern repeated on the left.
- Return value: String of exact length
len, orNULLon invalid orNULLinputs.
If padstr has multiple characters, MySQL repeats it as many times as needed and trims the partial repeat so the output measures len characters.
Practical Example
Your HR badge printer requires 6-character zero-padded codes from demo_employees. You can format employee_id and inspect how LPAD() handles values that exceed len.
SELECT
employee_id,
badge_code,
LPAD(employee_id, 6, '0') AS formatted_id,
LPAD(badge_code, 4, '*') AS short_badge
FROM demo_employees
ORDER BY employee_id;
| employee_id | badge_code | formatted_id | short_badge |
|---|---|---|---|
| 7 | EMP-07 | 000007 | EMP- |
| 42 | EMP-42 | 000042 | EMP- |
| 1050 | MGR-1050 | 001050 | MGR- |
Look at short_badge: because 'EMP-07' has 6 characters and len is 4, LPAD() truncates it from the right down to 'EMP-'!
Common Mistakes & NULL Behavior
- Silent right-truncation: When
CHAR_LENGTH(str) > len,LPAD()drops characters from the right end ofstrso the output stayslencharacters long. Always picklenlarge enough for your widest value. - Empty padstr returns NULL when padding is needed: Calling
LPAD('42', 5, '')returnsNULLin MySQL because an empty string cannot pad to length5. - Negative length returns NULL: Passing
len < 0returnsNULLrather than an empty string. - Any NULL argument returns NULL: If
str,len, orpadstrisNULL, the output isNULL.
Frequently Asked Questions
What happens if len equals the current length of str?
LPAD() returns str unchanged without adding any padstr characters.
Can LPAD() pad numbers directly without CAST()?
Yes. MySQL implicitly converts employee_id to '7' before padding it to '000007'.
How do I pad on the right side instead of the left?
Use RPAD(str, len, padstr) to append padding characters to the end of the string.
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.