How to update a specific column value fetched with CASE statement?


For this, use UPDATE command along with CASE statement. Let us first create a table −

mysql> create table DemoTable1925
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentMarks int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1925(StudentName,StudentMarks) values('Chris',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1925(StudentName,StudentMarks) values('David',45);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1925;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|         1 | Chris       |           98 |
|         2 | David       |           45 |
+-----------+-------------+--------------+
2 rows in set (0.00 sec)

Here is the query to update a specific column value fetched with CASE statement −

mysql> update DemoTable1925
   set StudentMarks=case StudentMarks when 45 then 98
   when 98 then 0 end
   where StudentMarks IN(45,98);
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1925;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|         1 | Chris       |            0 |
|         2 | David       |           98 |
+-----------+-------------+--------------+
2 rows in set (0.00 sec)

Updated on: 30-Dec-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements