Question about composite indexes and WHERE + GROUP BY
-
12-03-2021 - |
Domanda
Alrighty so I understand how composite indexes work with WHERE but what if a column in the middle of the index is in the GROUP BY, as follows:
CREATE TABLE `test` (
`a` VARCHAR(255) NOT NULL,
`b` VARCHAR(255) NOT NULL,
`c` VARCHAR(255) NOT NULL,
INDEX(`a`,`b`,`c`)
) ENGINE=InnoDB DEFAULT CHARSET='utf8';
SELECT * FROM test WHERE a = ? AND c = ? GROUP BY b
Would MySQL stop using the index before c
, or would it be able to use all three indexes in the above query since b
is in the GROUP BY. I haven't been able to find any resources on how exactly GROUP BY utilizes a composite index in a case like the above. In this case I'm using MySQL for database flavor.
Soluzione
The index isn't covering since B
isn't part of the WHERE
clause as a predicate, so the index is not applicable to this query. In other words, the index stores the data sorted by A
then by B
then by C
, but since you're only filtering on A
and C
, there's no direct way to seek out C
without B
. You might end up seeing an index scan or table scan get used instead, in this case.
Altri suggerimenti
Start with the =
parts of WHERE
:
INDEX(a, c, [to be continued]
Those can be in either order.
Now continue with the GROUP BY
:
INDEX(a, c, b)
Based on what you have shown us, that will be covering. (That is, all the needed columns anywhere in the query are in the index.)
See also http://mysql.rjweb.org/doc.php/index_cookbook_mysql