When to use NULL in MySQL tables

后端 未结 11 1856
春和景丽
春和景丽 2020-11-29 22:59

I appreciate the semantic meaning of a NULL value in a database table, different from both false and the empty string \'\'. However, I have often read about performance pro

11条回答
  •  时光取名叫无心
    2020-11-29 23:47

    The meaning of a NULL column is more or less "doesn't apply in this context". I generally use NULL columns in two cases:

    • If the field doesn't apply (let's say you have a boolean column is_thirsty and you add two datasets. One human and a stone. In case of the human, you set is_thirsty to either true or false, whereas in the case of the stone, you'd probably set it to NULL.
    • If I need to flag something and store some data with the value. Like an inventory close date, which you'd use to a) specify that the inventory cannot be changed any more and b) to specify when the inventory was closed. Instead of having two columns (closed_at and is_closed), I just create the closed_at column and set it to NULL if the inventory set can still be changed, but set the date once it's closed.

    Basically it boils down to the fact that I use NULL when the emptyness of a field has a different unique semantic than just an empty field. The absence of a middle initial is just that. The absence of a closing date has the meaning of the inventory set still being open to changes.

    NULL values can have nasty side effects and they will make life harder for you to add data to the table and more often than not, you can end up with a mish-mash of NULL values and empty strings for example.

    Also, NULL is not equal to anything, which will screw queries all over the place if you are not very careful.

    Personally, I use NULL columns only when one of the above two cases applies. I never use it to signify empty fields when the emptyness has no meaning other than the absence of a value.

提交回复
热议问题