SET only two values for all the rows in a MySQL table based on conditions?

MySQLMySQLi Database

For condition based update, use UPDATE and IF(). Let us first create a table −

mysql> create table DemoTable
(
   Value int
);
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    10 |
|    20 |
|    10 |
|    20 |
|    30 |
+-------+
5 rows in set (0.00 sec)

Following is the query to update based on a condition −

mysql> update DemoTable set Value=if(Value=10,20,10);
Query OK, 5 rows affected (0.20 sec)
Rows matched: 5 Changed: 5 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    20 |
|    10 |
|    20 |
|    10 |
|    10 |
+-------+
5 rows in set (0.00 sec)
raja
Published on 03-Oct-2019 11:09:30
Advertisements