How to update multiple rows and left pad values in MySQL?


Use the LPAD() function to left pad values. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (2.26 sec

Insert some records in the table using insert command −

mysql> insert into DemoTable values(857786);
Query OK, 1 row affected (0.26 sec)

mysql> insert into DemoTable values(89696);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values(89049443);
Query OK, 1 row affected (0.25 sec

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----------+
| Number   |
+----------+
| 857786   |
| 89696    |
| 89049443 |
+----------+
3 rows in set (0.00 sec)

Following is the query to update multiple rows and left pad values −

mysql> update DemoTable set Number=LPAD(Number, 7, "9") where length(Number) < 7;
Query OK, 2 rows affected (0.40 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----------+
| Number   |
+----------+
| 9857786  |
| 9989696  |
| 89049443 |
+----------+
3 rows in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements