SQL padding in SQL Server
Every pad idiom on SQL Server is a two-step: build the fill, then slice to width. Learn the two patterns and their silent truncation.
- 类别
- Strings
- Returns
string- In this category
- 38 of 172
语法
RIGHT('00000' + value, 5)
LEFT(value + ' ', 10)
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | Not built in | No built-in equivalent. |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
示例
SQL Server
SELECT RIGHT('00000' + CAST(region AS varchar(5)), 5) AS region_code
FROM stores;
SQL Server
SELECT LEFT(name + REPLICATE(' ', 12), 12) AS aligned FROM items;
值得了解
- RIGHT('00000' + CAST(n AS varchar(10)), 5) is the LPAD idiom; LEFT(name + REPLICATE(' ', 20), 20) is RPAD. Both slice to exactly the target width.
- The slice always truncates longer values: RIGHT('00000' + '123456', 5) is '23456'. There is no built-in that pads-or-keeps. Validate lengths when input is unbounded.
- FORMAT(n, '00000') pads numbers cleanly but is the slow option per row; the string idioms are cheap.
- The same gap exists in every SQL Server version to date: 2022 added TRIM(LEADING/TRAILING chars FROM s) and 2025 added ||, but neither added LPAD or RPAD.
Questions about Padding in SQL Server
Did SQL Server 2022 add LPAD?
No. LPAD and RPAD are still missing. 2022 added TRIM(LEADING/TRAILING chars FROM s) and 2025 added the || operator, so zero-padding still needs FORMAT or RIGHT+REPLICATE.
Why does my padded value lose digits?
The RIGHT/LEFT idiom truncates to the exact width; that is how it works. Pad to a width your data cannot exceed, or check LEN first.
Is there a CONCAT-side alternative?
CONCAT joins but does not pad. The fill-then-slice pattern is unavoidable on SQL Server; keep it in one view or function so the width rule lives in one place.
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.
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.