MySQL left padding with zeros separated by hyphen?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable829(SerialNumber int);
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable829 values(100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable829 values(101);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable829 values(102);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable829 values(103);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable829 values(104);
Query OK, 1 row affected (0.60 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable829;

This will produce the following output −

+--------------+
| SerialNumber |
+--------------+
|          100 |
|          101 |
|          102 |
|          103 |
|          104 |
+--------------+
5 rows in set (0.00 sec)

Following is the query to pad zeros separated by a hyphen −

mysql> select RIGHT(CONCAT('000-', SerialNumber), 7) from DemoTable829;

This will produce the following output −

+----------------------------------------+
| RIGHT(CONCAT('000-', SerialNumber), 7) |
+----------------------------------------+
| 000-100                                |
| 000-101                                |
| 000-102                                |
| 000-103                                |
| 000-104                                |
+----------------------------------------+
5 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 12:28:57
Advertisements