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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With