How to remove zeros from a number in sql?
The easiest way to remove leading zeros from a number in SQL, especially if the column is a string type (like VARCHAR or NVARCHAR), is to simply convert it to a numerical data type like INT or BIGINT and then back to a string if you need it as text again. Here’s how it typically works, and it's super common: 1. Cast to a Number and Back (The Quick Fix): In SQL Server, for example, you can use CAST
or CONVERT
. When a string like '000123'
is cast to an integer, the leading zeros are automatically dropped because integers don't store them. sql SELECT CAST(CAST('00012345' AS INT) AS VARCHAR(50)) AS NoLeadingZeros; -- Result: '12345'
Keep in mind: This only works if the string is purely numeric! If it has letters or other non-numeric characters (like a SKU '000AB123'), this will throw an error, so be careful with your data! 2. Using PATINDEX
and SUBSTRING
(The Flexible Approach): If your column contains mixed characters, or you want more control, you can use PATINDEX
to find the first non-zero character and SUBSTRING
to extract the rest of the string. sql SELECT SUBSTRING( YourStringColumn, PATINDEX('%[^0]%', YourStringColumn), LEN(YourStringColumn) ) AS CleanedString FROM YourTable;
PATINDEX('%[^0]%', YourStringColumn)
finds the position of the first character that is not a zero ([^0]
). SUBSTRING
then starts extracting the string from that position right up to the end. This is a robust way to handle leading zeros without converting types.
Hey there, I've dealt with this a lot when cleaning up customer IDs! The best method really depends on which flavor of SQL you're using (MySQL, PostgreSQL, SQL Server, etc.). For databases that support it, the new TRIM
function is a godsend for this, as it's the cleanest, most modern way to do it. * For SQL Server 2022+ or some modern SQL versions: You can use TRIM(LEADING '0' FROM YourStringColumn)
. This is super explicit and easy to read. * For PostgreSQL/MySQL: You can often use the LTRIM
function, but it only removes spaces by default. To remove zeros, you'll specifically need the TRIM
syntax, or often a function specific to removing leading characters. If you're stuck on an older version of SQL Server, I'd strongly recommend the PATINDEX
/SUBSTRING
method mentioned in the other answer—it's very reliable for strings, but if your data is guaranteed to be a number, the CAST
to INT
is definitely the fastest and simplest to write! Just remember, you're only removing the leading zeros, not the ones in the middle (like turning '00100'
into '100'
, not '1'
).