Converting boolean values to positive or negative sign in MySQL?

MySQLMySQLi Database

Following is the syntax −

select if(yourColumnName,1,-1) from yourTableName;

Let us first create a table −

mysql> create table DemoTable
(
   isMarried boolean
);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(true);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(true);
Query OK, 1 row affected (0.36 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| isMarried |
+-----------+
|         1 |
|         0 |
|         0 |
|         1 |
+-----------+
4 rows in set (0.00 sec)

Following is the query to convert boolean to a positive or negative sign in MySQL. Here, we have set negative for boolean false i.e. 0 −

mysql> select if(isMarried,1,-1) from DemoTable;

This will produce the following output −

+--------------------+
| if(isMarried,1,-1) |
+--------------------+
|                  1 |
|                 -1 |
|                 -1 |
|                  1 |
+--------------------+
4 rows in set (0.00 sec)
raja
Published on 30-Sep-2019 08:01:34
Advertisements