How to update all the entries except a single value in a particular column using MySQL?


To update all the entries while ignoring a single value, you need to use IF().

Let us first create a table −

mysql> create table DemoTable736 (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100),
   isMarried boolean
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable736(CustomerName,isMarried) values('Chris',0);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Robert',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('David',0);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Mike',0);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable736(CustomerName,isMarried) values('Bob',0);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable736;

This will produce the following output -

+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 0         |
| 2          | Robert       | 0         |
| 3          | David        | 0         |
| 4          | Mike         | 0         |
| 5          | Carol        | 1         |
| 6          | Bob          | 0         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)

Following is the query to update all the entries except a single value in a particular column using MySQL. Here, we are updating the “isMarried” column −

mysql> update DemoTable736 set isMarried=if(CustomerId=5,1,1);
Query OK, 5 rows affected (0.13 sec)
Rows matched: 6 Changed: 5 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable736;

This will produce the following output -

+------------+--------------+-----------+
| CustomerId | CustomerName | isMarried |
+------------+--------------+-----------+
| 1          | Chris        | 1         |
| 2          | Robert       | 1         |
| 3          | David        | 1         |
| 4          | Mike         | 1         |
| 5          | Carol        | 1         |
| 6          | Bob          | 1         |
+------------+--------------+-----------+
6 rows in set (0.00 sec)

Updated on: 22-Aug-2019

898 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements