Search code examples
mysqlindexingcomposite-keyquery-performancewhere-in

Why is MySQL not using indexes with composite WHERE IN?


I am trying to get several records by composite index from a table having PRIMARY KEY (a, b)

SELECT * FROM table WHERE (a, b) IN ((1,2), (2,4), (1,3))

The problem is, that MySQL is not using index, even if I FORCE INDEX (PRIMARY).
EXPLAIN SELECT shows null possible_keys.

Why there are no possible_keys?

What is the best way to retrieve multiple rows by composite key:

  • using OR
  • using UNION ALL
  • using WHERE () IN ((),())

P.S. Query is equal by result to

SELECT * FROM table WHERE (a = 1 AND b = 2) OR (a = 2 AND b = 4) OR (a = 1 AND b = 3)

Thanks


Solution

  • If query selects only fields from index (or if table has no other fields) by composite WHERE ... IN, index will be used:

    SELECT a,b FROM `table` WHERE (a, b) IN ((1,2), (2,4), (1,3))
    

    Otherwise it will not be used. The workaround is to use derived query:

    SELECT t.* FROM (SELECT a, b FROM `table` WHERE (a, b) IN ((1,2), (2,4), (1,3))) AS o INNER JOIN `table` AS t ON (t.a = o.a AND t.b = o.b)
    

    EXPLAIN SELECT:

    id  select_type table   type    possible_keys   key key_len ref rows    Extra
    1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    2   
    1   PRIMARY t   eq_ref  PRIMARY PRIMARY 2   o.a,o.b 1   
    2   DERIVED table   index   NULL    PRIMARY 2   NULL    6   Using where; Using index