lpad(text, integer, text) — Pad a string on the left
Last updated: 2026-11-04
lpad(text, integer, text) — Pad a string on the left
lpad() pads a string on the left with a fill character (a space by default) until it reaches the requested length, and truncates from the right when the string is already longer. Its typical jobs are producing fixed-width codes and zero-padding numbers, for example turning an order number into a uniform 8-character identifier.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
lpad(string text, length integer [, fill text]) → text
rpad(string text, length integer [, fill text]) → text
⚙️ Parameters
| string text | The string to pad. Type text. |
|---|---|
| length integer | The target total length in characters. Type integer. |
| fill text | Optional: the fill character, a space by default; it may be several characters long and is repeated as needed. Type text. |
Returns:text — the padded (or truncated) string.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | order_no | padded_code
----+----------+-------------
1 | 42 | 00000042
2 | 1234 | 00001234
3 | 987654 | 00987654
(3 rows)
📌 Key Points
- If the target length is shorter than the input the string is truncated: lpad('abcdef', 3, '0') returns 'abc'.
- The fill value may consist of several characters and is repeated as needed: lpad('hi', 5, 'xy') returns 'xyxhi'. The default fill is a space.
- Cast numbers with ::text before passing them to lpad().
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QCan lpad() overflow if the string grows too long?
ANo. The second argument is the final length: a longer input is truncated on the right, a shorter one is padded, so the result length always equals that argument.