Update multiple rows in a single column in MySQL?



To update multiple rows in a single column, use CASE statement. Let us first create a table −

mysql> create table updateMultipleRowsDemo    -> (    -> StudentId int,    -> StudentMathScore int    -> ); Query OK, 0 rows affected (0.63 sec)

Following is the query to insert records in the table using insert command −

mysql> insert into updateMultipleRowsDemo values(10001,67); Query OK, 1 row affected (0.14 sec) mysql> insert into updateMultipleRowsDemo values(10002,69); Query OK, 1 row affected (0.15 sec) mysql> insert into updateMultipleRowsDemo values(10003,89); Query OK, 1 row affected (0.14 sec) mysql> insert into updateMultipleRowsDemo values(10004,99); Query OK, 1 row affected (0.13 sec) mysql> insert into updateMultipleRowsDemo values(10005,92); Query OK, 1 row affected (0.13 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from updateMultipleRowsDemo;

This will produce the following output −

+-----------+------------------+ | StudentId | StudentMathScore | +-----------+------------------+ | 10001 | 67 | | 10002 | 69 | | 10003 | 89 | | 10004 | 99 | | 10005 | 92 | +-----------+------------------+ 5 rows in set (0.00 sec)

Here is the query to update multiple rows in a single column in MySQL −

mysql> UPDATE updateMultipleRowsDemo    -> SET StudentMathScore= CASE StudentId    -> WHEN 10001 THEN 45   -> WHEN 10002 THEN 52 -> WHEN 10003 THEN 67 -> END -> WHERE StudentId BETWEEN 10001 AND 10003; Query OK, 3 rows affected (0.19 sec) Rows matched: 3 Changed: 3 Warnings: 0

Let us check the value is updated or not −

mysql> select * from updateMultipleRowsDemo;

This will produce the following output

+-----------+------------------+ | StudentId | StudentMathScore | +-----------+------------------+ | 10001 | 45 | | 10002 | 52 | | 10003 | 67 | | 10004 | 99 | | 10005 | 92 | +-----------+------------------+ 5 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:25+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements