SQL zero-padding pattern
Turn 42 into 00042 for codes and fixed-width exports. Every engine has a native route; all of them share the truncation gotcha.
- Category
- Strings
- Returns
string- In this category
- 37 of 172
Syntax
LPAD(n::text, 5, '0')
printf('%05d', n)
FORMAT(n, '00000')
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Yes | Supported under this name. |
Examples
PostgreSQL
SELECT LPAD(420::text, 5, '0') AS padded; -- 00420
SQLite
SELECT printf('%05d', 42) AS padded; -- 00042
SQL Server
SELECT FORMAT(42, '00000') AS padded; -- 00042
Oracle
SELECT TO_CHAR(42, 'FM000000') AS padded FROM dual; -- 000042
Good to know
- LPAD truncates when the value is longer than the target width: LPAD('123456', 5, '0') is '12345', silently. Check lengths if the input is unbounded.
- The output is a string; casting it back to a number drops the zeros, and CSV/Excel may do the same on import.
- Oracle's TO_CHAR needs the FM prefix to suppress the sign placeholder: TO_CHAR(42, 'FM000000'), not '000000' which pads a leading blank.
- SQL Server has no LPAD: FORMAT(n, '00000') or RIGHT('00000' + CAST(n AS varchar(10)), 5) are the idioms.
Questions about Zero-padding numbers
Why does LPAD give me '12345' instead of '0012345'?
LPAD pads up to the target length and truncates anything longer. Widen the target or validate the input before padding.
How do I zero-pad in SQL Server?
FORMAT(n, '00000') for numbers, or the classic RIGHT('00000' + CAST(n AS varchar(10)), 5) when FORMAT's cost matters on large sets.
Why do my leading zeros disappear after export?
The zeros only exist in the string. Excel, casts and numeric columns all drop them. Keep the column textual end to end, or emit a format hint in CSV.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.