Is there a way in MySQL to reverse a boolean field with a single query?

MySQLMySQLi Database

Yes, you can use if() function from MySQL to reverse a boolean field. The syntax is as follows −

UPDATE yourTableName SET yourBooleanColumnName = IF(yourBooleanColumnName,0,1);

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table ReverseBooleanField
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> isValid BOOLEAN
   -> ,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.56 sec)

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

mysql> insert into ReverseBooleanField(isValid) values(true);
Query OK, 1 row affected (0.18 sec)

mysql> insert into ReverseBooleanField(isValid) values(false);
Query OK, 1 row affected (0.14 sec)

mysql> insert into ReverseBooleanField(isValid) values(true);
Query OK, 1 row affected (0.29 sec)

mysql> insert into ReverseBooleanField(isValid) values(true);
Query OK, 1 row affected (0.09 sec)

mysql> insert into ReverseBooleanField(isValid) values(false);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from ReverseBooleanField;

The following is the output −

+----+---------+
| Id | isValid |
+----+---------+
|  1 |       1 |
|  2 |       0 |
|  3 |       1 |
|  4 |       1 |
|  5 |       0 |
+----+---------+
5 rows in set (0.00 sec)

MySQL internally converts BOOLEAN to TINYINT(1) which gives true as 1 and false as 0.

Now, let us reverse boolean field in a single query −

mysql> update ReverseBooleanField set isValid = if(isValid,0,1);
Query OK, 5 rows affected (0.21 sec)
Rows matched − 5 Changed − 5 Warnings − 0

Check whether the boolean field is reversed or not using select statement. The query is as follows −

mysql> select *from ReverseBooleanField;

The following is the output −

+----+---------+
| Id | isValid |
+----+---------+
| 1  |       0 |
| 2  |       1 |
| 3  |       0 | 
| 4  |       0 |
| 5  |       1 |
+----+---------+
5 rows in set (0.00 sec)
raja
Published on 01-Feb-2019 10:21:25
Advertisements