Set different IDs for records with conditions using a single MySQL query

MySQLMySQLi Database

For conditions, use CASE statement in MySQL. Let us first create a table −

mysql> create table DemoTable1545
   -> (
   -> Id int,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (1.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1545 values(1,'John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1545 values(2,'Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1545 values(3,'Bob');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1545;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|    1 | John      |
|    2 | Chris     |
|    3 | Bob       |
+------+-----------+
3 rows in set (0.00 sec)

Here is the query to set different IDs using CASE statement −

mysql> update DemoTable1545
   -> set Id=
   -> case when FirstName like '%John%' then 101
   -> when FirstName like '%Chris%' then 201
   -> when FirstName like '%Bob%' then 501
   -> else Id
   -> end;
Query OK, 3 rows affected (0.18 sec)
Rows matched: 3  Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1545;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | John      |
|  201 | Chris     |
|  501 | Bob       |
+------+-----------+
3 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 10:38:53
Advertisements