Can we update MySQL with if condition?

MySQLMySQLi Database

You can update MySQL with IF condition as well as CASE statement. For this purpose, let us first create a table. The query to create a table −

mysql> create table UpdateWithIfCondition
   −> (
   −> BookId int,
   −> BookName varchar(200)
   −> );
Query OK, 0 rows affected (0.60 sec)

Now you can insert records in the table using insert command. The query is as follows −

mysql> insert into UpdateWithIfCondition values(1000,'C in Depth');
Query OK, 1 row affected (0.12 sec)

mysql> insert into UpdateWithIfCondition values(1001,'Introduction to Java');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from UpdateWithIfCondition;

The following is the output −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | C in Depth           |
| 1001   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)

Let us update the value ‘C in Depth’ with the value 'Introduction to C' and 1001 with the value 2000 using if condition. The query is as follows −

mysql> update UpdateWithIfCondition
   −> set BookName = if(BookName = 'C in Depth','Introduction to C',BookName),
   −> BookId = if(BookId = 1001,2000,BookId);
Query OK, 2 rows affected (0.43 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Above, we have updated both the column values. The following is the query to check both the two values have been updated or not −

mysql> select *from UpdateWithIfCondition;

The following is the output displaying that we have successfully updated the values using if −

+--------+----------------------+
| BookId | BookName             |
+--------+----------------------+
| 1000   | Introduction to C    |
| 2000   | Introduction to Java |
+--------+----------------------+
2 rows in set (0.00 sec)
raja
Published on 16-Jan-2019 12:57:36
Advertisements