What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field?
Field with value "00345ABC" would need to return "345ABC".
Join Stack Overflow to learn, share knowledge, and build your career.
What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field?
Field with value "00345ABC" would need to return "345ABC".
You are looking for the trim() function.
Alright, here is your example
SELECT TRIM(LEADING '0' FROM myfield) FROM table
SELECT 'A' + 0;
outputs 0 instead of 'A'. 'A' is not a number, but you're trying to add a number to it. So it converts both arguments to numbers. A
doesn't represent a number, so it's converted to 0. Give the MySQL documentation on Type Conversion a read.
– Dalendrion
Dec 23 '20 at 13:31
TIP:
If your values are purely numerical, you can also use simple casting, e.g.
SELECT * FROM my_table WHERE accountid = '00322994' * 1
will actually convert into
SELECT * FROM my_table WHERE accountid = 322994
which is sufficient solution in many cases and also I believe is performance more effective. (warning - value type changes from STRING to INT/FLOAT).
In some situations, using some casting function might be also a way to go:
If you want to update one entire column of a table, you can use
USE database_name;
UPDATE `table_name` SET `field` = TRIM(LEADING '0' FROM `field`) WHERE `field` LIKE '0%';
TRIM will allow you to remove the trailing, leading or all characters. Some examples on the use of the TRIM function in MySQL:
select trim(myfield) from (select ' test' myfield) t;
>> 'test'
select trim('0' from myfield) from (select '000000123000' myfield) t;
>> '123'
select trim(both '0' from myfield) from (select '000000123000' myfield) t;
>> '123'
select trim(leading '0' from myfield) from (select '000000123000' myfield) t;
>> '123000'
select trim(trailing '0' from myfield) from (select '000000123000' myfield) t;
>> '000000123'
If you want to remove only a select amount of leading/trailing characters, look into the LEFT/RIGHT functions, with combination of the LEN and INSTR functions
just remove space between TRIM ( LEADING
use
SELECT * FROM my_table WHERE TRIM(LEADING '0' FROM accountid ) = '00322994'
SELECT TRIM(LEADING '0' FROM *columnName*) FROM *tableName* ;
This also work correctly