Are there reasons for not storing boolean values in SQL as bit data types?

后端 未结 11 1578
北恋
北恋 2020-12-29 02:44

Are there reasons for not storing boolean values in SQL as bit data types without NULL? I see them often stored as integers without constraints to limit values to 0 and 1,

相关标签:
11条回答
  • 2020-12-29 02:54

    I think third normalization form would state that you should have a table that stores the values True and False, and reference that. Make sure you do that with your dates as well!

    But who completely adheres to 3NF anyway? ;)

    0 讨论(0)
  • 2020-12-29 02:55

    I see them often stored as integers without constraints to limit values to 0 and 1, and as strings with things like T/F, True/False, yes/no, etc., again without constraints. Isn't it better to store them as bits and not have to worry about additional constraints?

    Yes!

    What am I missing here?

    Actually it should be "what am I NOT missing here?" and the answer would be: common sense.

    0 讨论(0)
  • 2020-12-29 03:00

    I'd always stick with the smallest data type I can to store this.

    • SQLServer: BIT
    • Oracle: NUMBER(1) (or BOOLEAN in PL/SQL)
    • MySQL: TINYINT (iirc BOOLEAN maps to this automatically)

    Edit: Oracle's BOOLEAN is PL/SQL only, not table definition. Updated answer to reflect this.

    0 讨论(0)
  • 2020-12-29 03:00

    I use bit a lot. But sometimes I want to be able to have the ability to return false - or many values of true (like error messaging). So if I use an int instead of boolean I can doe something like:

    0 = False 1 = Password incorrect 2 = Username does not exist. 3 = Account locked out - to many failed attempts. 4 = Account disabled.

    And so on.

    0 讨论(0)
  • 2020-12-29 03:02

    BIT is the datatype normally used to store BOOLEAN values. Simply because if the BIT is 1 then its true and 0 then its false. It is that simple.

    0 讨论(0)
  • 2020-12-29 03:03

    When I want booleans in the database I always use the bit data type. In SQL they can be NULL. But when running your program you'll have to consider that a bool (e.g. in C#) is a value type which in this case can't be NULL. You'll have to compare with the System.DBNull value.

    0 讨论(0)
提交回复
热议问题