MySQL Mass Update with CASE WHEN/ THEN/ ELSE?

MySQLMySQLi Database

The syntax for mass update with CASE WHEN/ THEN/ ELSE is as follows −

UPDATE yourTableName set yourColumnName=case when yourColumnName=Value1 then anyUpdatedValue1
when yourColumnName=Value2 then anyUpdatedValue2
when yourColumnName=Value3 then anyUpdatedValue3
when yourColumnName=Value4 then anyUpdatedValue4
else yourColumnName
end;

To understand the above syntax, let us first create a table. The query to create a table is as follows −

mysql> create table CaseUpdateDemo
-> (
-> Id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into CaseUpdateDemo values(1,'John');
Query OK, 1 row affected (0.17 sec)

mysql> insert into CaseUpdateDemo values(2,'Carol');
Query OK, 1 row affected (0.27 sec)

mysql> insert into CaseUpdateDemo values(3,'Mike');
Query OK, 1 row affected (0.11 sec)

mysql> insert into CaseUpdateDemo values(4,'Bob');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from CaseUpdateDemo;

Output

+------+-------+
| Id   | Name  |
+------+-------+
| 1    | John  |
| 2    | Carol |
| 3    | Mike  |
| 4    | Bob   |
+------+-------+
4 rows in set (0.00 sec)

Now you can write the query we discussed above to update column id with Case WHEN THEN ELSE. The query is as follows −

mysql> update CaseUpdateDemo set Id=case when Id=1 then 1001
-> when Id=2 then 1002
-> when Id=3 then 1003
-> when Id=4 then 1004
-> else Id
-> end;
Query OK, 4 rows affected (0.15 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Now you can check whether the table is updated for ID column using select statement. The query is as follows −

mysql> select *from CaseUpdateDemo;

Output

+------+-------+
| Id   | Name  |
+------+-------+
| 1001 | John  |
| 1002 | Carol |
| 1003 | Mike  |
| 1004 | Bob   |
+------+-------+
4 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 10:50:55
Advertisements