Which MySQL data type to use for storing boolean values

前端 未结 13 1599
感情败类
感情败类 2020-11-22 04:45

Since MySQL doesn\'t seem to have any \'boolean\' data type, which data type do you \'abuse\' for storing true/false information in MySQL?

Especially in the context

相关标签:
13条回答
  • 2020-11-22 05:28

    Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use

    bool_val TINYINT CHECK(bool_val IN(0,1))
    

    You will only be able to store 0, 1 or NULL, as well as values which can be converted to 0 or 1 without errors like '1', 0x00, b'1' or TRUE/FALSE.

    If you don't want to permit NULLs, add the NOT NULL option

    bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))
    

    Note that there is virtually no difference if you use TINYINT, TINYINT(1) or TINYINT(123).

    If you want your schema to be upwards compatible, you can also use BOOL or BOOLEAN

    bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))
    

    db<>fiddle demo

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