Tinyint vs Bit?

前端 未结 16 2061
暖寄归人
暖寄归人 2020-12-13 05:13

I don\'t want to touch-off a religious war here, but there seem to be two schools of thoughts in how to represent boolean values in a database. Some say bit is

相关标签:
16条回答
  • 2020-12-13 06:09

    If you're using MySQL, then it's not recommended to use the BIT data type - http://www.xaprb.com/blog/2006/04/11/bit-values-in-mysql/

    0 讨论(0)
  • 2020-12-13 06:11

    When you add a bit column to your table it will occupy a whole byte in each record, not just a single bit. When you add a second bit column it will be stored in the same byte. The ninth bit column will require a second byte of storage. Tables with 1 bit column will not gain any storage benefit.

    Tinyint and bit can both be made to work, I have used both successfully and have no strong preference.

    0 讨论(0)
  • 2020-12-13 06:11

    Zero Space for False

    Whatever your choice, you can set to NULL instead of 0 and it will take up no extra space (since the database almost always has a NULL flag for every field of every row, just sitting there; more info here). If you also make sure the default/most likely value is false, you'll save even more space!

    Some Space for True

    The value to represent true requires the space defined by the field type; using BIT will only save space if a table has multiple such columns, since it uses one byte per 8 fields (versus TINYINT which uses one byte per field).

    TINYINT has the advantage of allowing you to customize an 8-value bitmask without worrying about managing a bunch of extra columns, and searching is theoretically faster (a single integer field versus several bit fields). But there are some disadvantages such as slower ordering, fancy cross-indexing stuff, and lack of field names. Which to me, is the biggest loss; your database would require external documentation to note which bits did what in which bitmasks.

    In any case, avoid the temptation to use TEXT fields to store booleans or sets of them. Searching through text is a lot more work for the server, and arbitrary naming schemes like "on, off, off" can hurt interoperability.

    0 讨论(0)
  • 2020-12-13 06:11

    We build all our tables with an int "vector" field. We then use that field as a collection of 32 bits that we can assign for any purpose. (Potentially using a group of bits for a set of states). Avoids us having to keep adding in flag fields if we forget.

    0 讨论(0)
  • 2020-12-13 06:12

    A previous StackOverflow post: What is the difference between BIT and TINYINT in MySQL?

    When adding a new "BOOL" column, MySQL actually uses TINYINT.

    I'd just stick with BOOL (aka TINYINT) and move on with life.

    0 讨论(0)
  • 2020-12-13 06:14

    I like using char(1) with 'T' or 'F'. Yes it can be abused with other values but at least it is easy to view in reports or other places where bit or binary values are harder to work with.

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