SQL trim leading zeros
Turn 000420 into 420. The one-liner is a character-set left trim; only SQL Server before 2022 needs a longer recipe.
- カテゴリ
- Strings
- Returns
string- In this category
- 41 of 172
構文
LTRIM(s, '0')
TRIM(LEADING '0' FROM s)
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | LTRIM(s, '0') from SQL Server 2022; PATINDEX + SUBSTRING before that |
| PostgreSQL | はい | Supported under this name. |
| MySQL | はい | TRIM(LEADING '0' FROM s); MySQL's LTRIM takes no character set |
| SQLite | はい | Supported under this name. |
| Oracle | はい | Supported under this name. |
例
PostgreSQL
SELECT LTRIM('000420', '0') AS n; -- 420
MySQL
SELECT TRIM(LEADING '0' FROM '000420') AS n; -- 420
SQLite
SELECT ltrim('000420', '0') AS n; -- 420
SQL Server
-- before SQL Server 2022, which has LTRIM(code, '0')
SELECT SUBSTRING(code, PATINDEX('%[^0]%', code + '1'), LEN(code)) AS n
FROM items;
知っておくと便利なこと
- It removes every leading zero, not exactly five: 00000120 becomes 120. That is usually the goal, but it is not a fixed-width substring.
- An all-zeros string trims to empty, and on Oracle '' is NULL, so LTRIM('000', '0') IS NULL. Guard with NULLIF/COALESCE as needed.
- Casting to a number also drops the zeros but reformats everything else (decimal separators, scientific notation); trim when the value is a code, cast when it is a quantity.
- Do not reach for SQLite's trim(s, '0'): it strips both ends, so '000420' becomes '42'. ltrim(s, '0') is the leading-only form.
Questions about Trimming leading zeros
Why is my trimmed all-zero value NULL on Oracle?
Oracle treats the empty result as NULL: LTRIM('000', '0') IS NULL is true there. Wrap with COALESCE(..., '0') when a zero value must survive.
Does SQL Server LTRIM support a character set?
From SQL Server 2022, yes: LTRIM('000420', '0') is '420'. On 2019 and older LTRIM strips spaces only, so SUBSTRING with PATINDEX('%[^0]%', s + '1') finds the first non-zero instead.
Should I trim zeros or cast to a number?
Codes that can regain or lose meaning (prefixes, checksums) should be trimmed as text; pure quantities can be cast, but the cast reformats, not just unpads.
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.