How to update multiple rows using single WHERE clause in MySQL?

MySQLMySQLi Database

For this, you can use MySQL IN(). Let us first create a −

mysql> create table DemoTable1420
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstName varchar(20),
   -> LastName varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (1.12 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Chris','Brown',23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('David','Miller',22);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Smith',24);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('John','Doe',21);
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable1420(FirstName,LastName,Age) values('Adam','Smith',25);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select −

mysql> select * from DemoTable1420;

This will produce the following output −

+----+-----------+----------+------+
| Id | FirstName | LastName | Age  |
+----+-----------+----------+------+
|  1 | Chris     | Brown    |   23 |
|  2 | David     | Miller   |   22 |
|  3 | John      | Smith    |   24 |
|  4 | John      | Doe      |   21 |
|  5 | Adam      | Smith    |   25 |
+----+-----------+----------+------+
5 rows in set (0.00 sec)

Following is the query to update multiple rows using single where clause −

mysql> update DemoTable1420
   -> set FirstName='Carol',LastName='Taylor'
   -> where Id IN(1,3,4,5);
Query OK, 4 rows affected (0.42 sec)
Rows matched: 4  Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1420;

This will produce the following output −

+----+-----------+----------+------+
| Id | FirstName | LastName | Age  |
+----+-----------+----------+------+
|  1 | Carol     | Taylor   | 23   |
|  2 | David     | Miller   | 22   |
|  3 | Carol     | Taylor   | 24   |
|  4 | Carol     | Taylor   | 21   |
|  5 | Carol     | Taylor   | 25   |
+----+-----------+----------+------+
5 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 05:31:07
Advertisements