Summary: this tutorial shows you how to use MySQL BOOLEAN data type to store Boolean values, true and false. Introduction to MySQL BOOLEAN data typeMySQL does not have built-in Boolean type. However, it uses 0 instead. To make it more convenient, MySQL provides 1 or 2 as the synonym of 0. In MySQL, zero is considered as false, and non-zero value is considered as true. To use Boolean literals, you use the constants 4 and 5 that evaluate to 1 and 0 respectively. See the following example:
MySQL BOOLEAN exampleMySQL stores Boolean value in the table as an integer. To demonstrate this, let’s look at the following 6 table:
Even though we specified the completed column as 1, when we show the table definition, it is 0 as follows:
The following statement inserts 2 rows into the 6 table:
Before saving data into the Boolean column, MySQL converts it into 1 or 0. The following query retrieves data from 6 table:
As you see, the 1 and 2 were converted to 1 and 0. Because Boolean is 0, you can insert value other than 1 and 0 into the Boolean column. Consider the following example:
It is working fine. If you want to output the result as 1 and 2, you can use the 6 function as follows:
MySQL BOOLEAN operatorsTo get all completed tasks in the 6 table, you might come up with the following query:
As you see, it only returned the task with 8 value 1. To fix it, you must use 9 operator:
In this example, we used the 9 operator to test a value against a Boolean value. To get the pending tasks, you use 1 or 2 as follows:
In this tutorial, you have learned how to use the 3 data type, which is the synonym of 0, and how to manipulate Boolean values. |