Which MySQL data type to use for storing boolean values?

 

In MySQL, you can use the TINYINT data type to store boolean values. Typically, boolean values are represented as 0 for false and 1 for true in MySQL using the TINYINT(1) data type. Here's an example:

sql
-- Create a table with a boolean column CREATE TABLE users ( user_id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), is_active TINYINT(1) ); -- Insert data into the table INSERT INTO users (username, is_active) VALUES ('user1', 1), -- true ('user2', 0); -- false

In this example:

  • We create a table named users with three columns: user_id, username, and is_active.

  • The is_active column is of type TINYINT(1), which is used to store boolean values. It can store 0 for false or 1 for true.

  • We insert two rows into the users table, where the is_active column represents boolean values. 'user1' is active (1 or true), and 'user2' is not active (0 or false).

You can use the TINYINT(1) data type to efficiently store boolean values in MySQL while using minimal storage space. When you query the database, you can treat 0 as false and 1 as true to work with boolean data effectively.

Comments