MySQL Forums
Forum List  »  Newbie

Re: best for true or false, Yes or No
Posted by: Rick James
Date: May 04, 2014 11:08PM

There is no 'perfect' answer.

Perhaps the most common is
TINYINT UNSIGNED NOT NULL
It takes exactly 1 byte. Put a 0 or 1 in it. Note that 0=FALSE and 1=TRUE and the WHERE clause is happy to handle
WHERE flag -- TRUE if 1; you don't need
WHERE flag=1

Perhaps the second choice is
ENUM NOT NULL
It is especially handy if there might eventually be more than 2 values: M/F/G/L/T/...' 'yes'/'no'/'maybe'; etc It takes 1 byte (for up to 255 choices).

Using NULL versus NOT NULL (together with some datatype) is tempting, but it means that changing the value could change the length of the record, thereby possibly causing a minor upheaval in the data.

Using CHAR(1) for 'Y'/'N', 'M'/'F', etc is tempting. But, with a default of utf8, that takes 3 bytes. That can be brought back to 1 byte by explicitly saying CHARACTER SET ascii (or latin1). (But most people fail to think about that.)

VARCHAR needs a length field, plus the text in question. So, at best, it is 1-2 bytes.

SET and INT let you combine multiple 'flags' into a single field. This is the most compact since you can get up to 8 flags per byte. But the coding is arguably more complex than it is worth. (Be sure to use TINYINT/SMALLINT/etc, depending on the number of flags.)

A related note...
INDEX(flag_column) is almost never useful. The optimizer would rather do a table scan instead of bouncing between the index and the data.
INDEX(flag, other_column) is sometimes useful.

Another thing that is sometimes done: Suppose you have a "soft" delete; that is, you set a flag saying that a row is "deleted" rather than actually deleting it. Another approach is to copy the row to another table and really delete it. Then use UNION for the few cases where you need to SELECT both deleted and active rows.

PARTITIONing can do a trick like the soft delete, but that seems even messier.

Options: ReplyQuote


Subject
Written By
Posted
Re: best for true or false, Yes or No
May 04, 2014 11:08PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.