MySQL query to add 0's to numbers with less than 9 digits?

MySQLMySQLi Database

Use LPAD() to add 0's to numbers with less than 9 digits. Let us first create a table −

mysql> create table DemoTable
(
   Value varchar(20)
);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('3646465');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values('9485757591');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('485756');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('959585');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('124');
Query OK, 1 row affected (0.27 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+
| Value      |
+------------+
| 3646465    |
| 9485757591 |
| 485756     |
| 959585     |
| 124        |
+------------+
5 rows in set (0.00 sec)

Following is the query to add 0's to numbers with less than 9 digits −

mysql> select lpad(Value,9,'0') from DemoTable;

This will produce the following output −

+-------------------+
| lpad(Value,9,'0') |
+-------------------+
| 003646465         |
| 948575759         |
| 000485756         |
| 000959585         |
| 000000124         |
+-------------------+
5 rows in set (0.03 sec)
raja
Updated on 30-Jul-2019 22:30:25

Advertisements