MySQL: “= true” vs “is true” on BOOLEAN. When is it advisable to use which one? And Which one is vendor independent?

前端 未结 2 1694
忘掉有多难
忘掉有多难 2020-12-23 19:49

MySQL provides 2 ways to check truth value of boolean columns, those are column_variable = true and column_variable is true. I created

相关标签:
2条回答
  • 2020-12-23 20:12

    If the flag column is indexed and all values are either 0 or 1, where flag = true is much faster than where flag is true.

    During our testing, is true resulted in a “full table scan” and took 1.121 seconds, while = true was executed with “key lookup” and only took 0.167 seconds. The table had about 3 million rows.

    0 讨论(0)
  • 2020-12-23 20:28

    MySQL is actually fooling you. It doesn't have a boolean column type at all:

    BOOL, BOOLEAN

    These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true:

    Also, the boolean literals are not such:

    The constants TRUE and FALSE evaluate to 1 and 0, respectively.

    Considering that:

    • Many database systems do not have booleans either (not at least in standard SQL and column types)
    • MySQL doesn't have an easy way to enforce 0 or 1 in BOOLEAN

    My conclusion would be:

    • You'll have to use WHERE IS flag or just WHERE flag because = simply doesn't work correctly. Which one, is possibly a matter of preference.
    • Whatever you choose, no option will be vendor independent. For instance, Oracle won't even run either of them.

    Edit: if cross-platform is a must, I'd go for this:

    WHERE flag=0
    WHERE flag<>0
    

    I'm sure we've all done it lots of times.

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