Create boolean column in MySQL with false as default value?

Mysql

Mysql Problem Overview


I want to create a table in MySQL with a boolean column whose default value is false. But it's accepting NULL as default...

Mysql Solutions


Solution 1 - Mysql

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0
);

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

Solution 2 - Mysql

You can set a default value at creation time like:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);

Solution 3 - Mysql

Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.

ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'

Solution 4 - Mysql

If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser169258View Question on Stackoverflow
Solution 1 - MysqlAsaphView Answer on Stackoverflow
Solution 2 - MysqlArchana ShahView Answer on Stackoverflow
Solution 3 - MysqlGaurav SethiView Answer on Stackoverflow
Solution 4 - MysqlVenkatesh LaguduvaView Answer on Stackoverflow