Introduction to MySQL BOOLEAN Data Type

The MySQL BOOLEAN data type is used to store boolean values, which can be TRUE or FALSE. In MySQL, BOOLEAN is actually an alias for TINYINT(1).

Syntax

The syntax for creating a BOOLEAN data type is as follows:

column_name BOOLEAN

where column_name is the name of the column to be created.

Use Cases

The BOOLEAN data type is commonly used for storing logical values, such as switch status, completion status, etc.

Examples

Here are two examples of using the BOOLEAN data type:

Example 1

Assuming we have a table called employees that contains employee ID, name, and employment status. We can create the table using the following SQL statement:

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    is_employed BOOLEAN
);

Then, we can insert some data:

INSERT INTO employees VALUES
(1, 'Alice', TRUE),
(2, 'Bob', FALSE),
(3, 'Charlie', TRUE);

Next, we can query the employees table to see the employment status of each employee:

SELECT name, is_employed FROM employees;

The query result will be:

+---------+-------------+
| name    | is_employed |
+---------+-------------+
| Alice   | 1           |
| Bob     | 0           |
| Charlie | 1           |
+---------+-------------+

Note that MySQL converts TRUE to 1 and FALSE to 0.

Example 2

Assuming we have a table called tasks that contains task ID, description, and completion status. We can create the table using the following SQL statement:

CREATE TABLE tasks (
    id INT PRIMARY KEY,
    description VARCHAR(50),
    is_completed BOOLEAN
);

Then, we can insert some data:

INSERT INTO tasks VALUES
(1, 'Clean the kitchen', TRUE),
(2, 'Buy groceries', FALSE),
(3, 'Do laundry', FALSE);

Next, we can query the tasks table to see the completion status of each task:

SELECT description, is_completed FROM tasks;

The query result will be:

+-----------------+--------------+
| description     | is_completed |
+-----------------+--------------+
| Clean the kitchen | 1           |
| Buy groceries    | 0           |
| Do laundry       | 0           |
+-----------------+--------------+

Conclusion

The BOOLEAN data type is a useful data type in MySQL for storing boolean values, such as switch status, completion status, etc. When using the BOOLEAN data type, it’s important to note that MySQL converts TRUE to 1 and FALSE to 0.