Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to trim leading zeros from alphanumeric text in mysql function

Tags:

mysql

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".

like image 200
Sean Avatar asked Sep 18 '08 21:09

Sean


People also ask

How do I remove leading zeros in MySQL?

MySQL TRIM() function returns a string after removing all prefixes or suffixes from the given string. Indicates that prefixes from both left and right are to be removed. Indicates that only leading prefixes are to be removed. Indicates that only trailing prefixes is to be removed.

What does trim function do in MySQL?

The TRIM() function removes leading and trailing spaces from a string.

How do I remove leading zeros from alphanumeric text string in Excel?

Press CTRL+1 (Format Cells shortcut). Select General on the Number tab, then press ENTER. No leading zeros for all numbers.


3 Answers

You are looking for the trim() function.

Alright, here is your example

SELECT TRIM(LEADING '0' FROM myfield) FROM table
like image 50
Chris Bartow Avatar answered Oct 17 '22 17:10

Chris Bartow


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:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

like image 43
lubosdz Avatar answered Oct 17 '22 19:10

lubosdz


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%';
like image 16
theBuzzyCoder Avatar answered Oct 17 '22 19:10

theBuzzyCoder