Is there any performance gain in indexing a boolean field?

后端 未结 7 1855
独厮守ぢ
独厮守ぢ 2020-12-02 10:39

I\'m just about to write a query that includes a WHERE isok=1. As the name implies, isok is a boolean field (actually a TINYINT(1) UNSIGNED

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 10:58

    It depends on the actual queries and the selectivity of the index/query combination.

    Case A: condition WHERE isok = 1 and nothing else there:

    SELECT *
    FROM tableX
    WHERE isok = 1
    
    • If the index is selective enough (say you have 1M rows and only 1k have isok = 1), then the SQL engine will probably use the index and be faster than without it.

    • If the index is not selective enough (say you have 1M rows and more than 100k have isok = 1), then the SQL engine will probably not use the index and do a table scan.

    Case B: condition WHERE isok = 1 and more stuff:

    SELECT *
    FROM tableX
    WHERE isok = 1
      AND another_column = 17
    

    Then, it depends on what other indexes you have. An index on another_column would probably be more selective than the index on isok which has only two possible values. An index on (another_column, isok) or (isok, another_column) would be even better.

提交回复
热议问题