So a few years ago I saw the DB schema of a system developed by a 3rd party and noticed they used enum('y','n') instead of a boolean (tinyint) field. I don't know why but I loved it so much, I found it made things easier to read (totally subjective I know) but I adopted it and started using it ever since then. I suppose I could swap it for "true" and "false" but, what can I say, I just liked it.
Now that being said, are there any setbacks to doing things this way -- aside from maybe slightly annoying a programmer who'd come in late in the game?
The ENUM data type in MySQL is a string object. It allows us to limit the value chosen from a list of permitted values in the column specification at the time of table creation. It is short for enumeration, which means that each column may have one of the specified possible values.
MySQL does not have a boolean (or bool) data type. Instead, it converts boolean values into integer data types (TINYINT). When you create a table with a boolean data type, MySQL outputs data as 0, if false, and 1, if true.
MySQL does not provide a built-in Boolean data type. It uses TINYINT(1) instead which works the same.
Empty or NULL Enumeration Values If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value.
Yes, it is bad. You lose intuitive boolean logic with it (SELECT * FROM user WHERE NOT banned
becomes SELECT * FROM user WHERE banned = 'n'
), and you receive strings instead of booleans on your application side, so your boolean conditions there become cumbersome as well. Other people who work with your schema will get bitten by seeing flag-like column names and attempting to use boolean logic on them.
As explained in the manual:
If you insert an invalid value into an
ENUM
(that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a “normal” empty string by the fact that this string has the numeric value 0. See Section 11.4.4, “ Index Values for Enumeration Literals ” for details about the numeric indexes for the enumeration values.If strict SQL mode is enabled, attempts to insert invalid
ENUM
values result in an error.
In this respect, an ENUM
results in different behaviour to a BOOLEAN
type; otherwise I'm inclined to agree with @lanzz's answer that it makes integration with one's application that little bit less direct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With