// strings reference

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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.