Any disadvantages to bit flags in database columns?

前端 未结 4 871
野趣味
野趣味 2020-12-30 07:27

Consider the following tables:

CREATE TABLE user_roles(
    pkey         SERIAL PRIMARY KEY,
    bit_id       BIGINT NOT NULL,
    name         VARCHAR(256)         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-30 07:59

    If you only have a handful of roles, you don't even save any storage space in PostgreSQL. An integer column uses 4 bytes, a bigint 8 bytes. Both may require alignment padding:

    • Making sense of Postgres row sizes
    • Calculating and saving space in PostgreSQL

    A boolean column uses 1 byte. Effectively, you can fit four or more boolean columns for one integer column, eight or more for a bigint.

    Also take into account that NULL values only use one bit (simplified) in the NULL bitmap.

    Individual columns are easier to read and index. Others have commented on that already.

    You could still utilize indexes on expressions or partial indexes to circumvent problems with indexes ("non-sargable"). Generalized statements like:

    database cannot use indexes on a query like this

    or

    These conditions are non-SARGable!

    are not entirely true - maybe for some others RDBMS lacking these features.
    But why circumvent when you can avoid the problem altogether?

    As you have clarified, we are talking about 6 distinct types (maybe more). Go with individual boolean columns. You'll probably even save space compared to one bigint. Space requirement seems immaterial in this case.


    If these flags were mutually exclusive, you could use one column of type enum or a small look-up table and a foreign key referencing it. (Ruled out in question update.)

提交回复
热议问题