Add leading zeros to a MySQL column?

MySQLMySQLi Database

To add leading zeros, you can use LPAD(). Let us first create a table −

mysql> create table DemoTable
(
   Code varchar(100)
);
Query OK, 0 rows affected (0.87 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('JS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('CB');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('DM');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('CT');
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+
| Code |
+------+
|   JS |
|   CB |
|   DM |
|   CT |
+------+
4 rows in set (0.00 sec)

Now, let us add leading zeros in MySQL −

mysql> update DemoTable set Code=LPAD(Code, 8, '0');
Query OK, 4 rows affected (0.10 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----------+
| Code     |
+----------+
| 000000JS |
| 000000CB |
| 000000DM |
| 000000CT |
+----------+
4 rows in set (0.00 sec)
raja
Published on 26-Sep-2019 06:53:19
Advertisements