Since MySQL doesn\'t seem to have any \'boolean\' data type, which data type do you \'abuse\' for storing true/false information in MySQL?
Especially in the context
Bit is only advantageous over the various byte options (tinyint, enum, char(1)) if you have a lot of boolean fields. One bit field still takes up a full byte. Two bit fields fit into that same byte. Three, four,five, six, seven, eight. After which they start filling up the next byte. Ultimately the savings are so small, there are thousands of other optimizations you should focus on. Unless you're dealing with an enormous amount of data, those few bytes aren't going to add up to much. If you're using bit with PHP you need to typecast the values going in and out.
For MySQL 5.0.3 and higher, you can use BIT
. The manual says:
As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.
Otherwise, according to the MySQL manual you can use BOOL
or BOOLEAN
, which are at the moment aliases of tinyint(1):
Bool, Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
MySQL also states that:
We intend to implement full boolean type handling, in accordance with standard SQL, in a future MySQL release.
References: http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html
This is an elegant solution that I quite appreciate because it uses zero data bytes:
some_flag CHAR(0) DEFAULT NULL
To set it to true, set some_flag = ''
and to set it to false, set some_flag = NULL
.
Then to test for true, check if some_flag IS NOT NULL
, and to test for false, check if some_flag IS NULL
.
(This method is described in "High Performance MySQL: Optimization, Backups, Replication, and More" by Jon Warren Lentz, Baron Schwartz and Arjen Lentz.)
I use TINYINT(1) in order to store boolean values in Mysql.
I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)
http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html
You can use BOOL, BOOLEAN data type for storing boolean values.
These types are synonyms for TINYINT(1)
However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.
MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).
Further, read documentation
This question has been answered but I figured I'd throw in my $0.02.
I often use a CHAR(0)
, where '' == true and NULL == false
.
From mysql docs:
CHAR(0)
is also quite nice when you need a column that can take only two values: A column that is defined asCHAR(0)
NULL
occupies only one bit and can take only the valuesNULL
and''
(the empty string).