Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Add 0's to numbers with less than 9 digits

I have thousands of entries in my database, each with 9 digits or less. I would like to do a mass update, find all rows with digits less than 9 and add 0's to make them equal 9 digits.

For example, my table looks like:

ID  |  Number  
---------------
0   |  489379
1   |  854744329
2   |  56456669

I would like to make it look like:

ID  |  Number  
---------------
0   |  000489379
1   |  854744329
2   |  056456669

How would I do this with a MySQL query?

like image 772
steeped Avatar asked Jun 04 '15 20:06

steeped


People also ask

How do I increment in MySQL?

Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

What is Zerofill in MySQL?

Zerofill pads the displayed value of the field with zeros up to the display width specified in the column definition. For example, if column is set int(8), therefore the width is 8.


1 Answers

The lpad function should solve your issue:

SELECT `id`, LPAD(`Number`, 9, '0')
FROM   mytable

To answer the question in the comment, this can also be applied in an update statement:

UPDATE mytable
SET    `Number` = LPAD(`Number`, 9, '0')
WHERE  LENGTH(`Number`) < 9
like image 70
Mureinik Avatar answered Sep 29 '22 06:09

Mureinik