How to convert bool to int in MySQL?

MySQLMySQLi Database

To convert bool to int in MySQL, you can use CAST(). Let us first create a table:

mysql> create table convertBoolToIntDemo
   -> (
   -> isYoung bool
   -> );
Query OK, 0 rows affected (0.69 sec)

Following is the query to insert some records in the table using insert command:

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

mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.09 sec)

mysql> insert into convertBoolToIntDemo values(true);
Query OK, 1 row affected (0.15 sec)

mysql> insert into convertBoolToIntDemo values(false);
Query OK, 1 row affected (0.18 sec)

Following is the query to display records from the table using select command:

mysql> select *from convertBoolToIntDemo;

This will produce the following output

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

Following is the query to convert bool to int in MySQL:

mysql> select cast(isYoung=1 AS SIGNED INTEGER) from convertBoolToIntDemo;

This will produce the following output

+-----------------------------------+
| cast(isYoung=1 AS SIGNED INTEGER) |
+-----------------------------------+
|                                 1 |
|                                 0 |
|                                 1 |
|                                 0 |
+-----------------------------------+
4 rows in set (0.00 sec)
raja
Published on 17-Apr-2019 11:24:19
Advertisements