This is for InnoDB with MySQL 5.7.
I have a set of 4 related cascading queries:
SELECT DISTINCT A, COUNT(*) FROM MYTABLE
WHERE D IN ? AND A > ?
GROUP BY A ORDER BY A LIMIT 100
SELECT DISTINCT B, COUNT(*) FROM MYTABLE
WHERE A = ? AND D IN ? AND B > ?
GROUP BY B ORDER BY B LIMIT 100
SELECT DISTINCT C, COUNT(*) FROM MYTABLE
WHERE A = ? AND B = ? AND D IN ? AND C > ?
GROUP BY C ORDER BY C LIMIT 100
SELECT E, F, G, H FROM MYTABLE
WHERE A = ? AND B = ? AND C = ? AND D IN ? AND ID > ?
ORDER BY ID LIMIT 100
What is the minimum set of index(es) such that all the queries can use one of the index(es) to prune by each of their WHERE clauses and also use it/them to speed up the ORDER BY?
From what I understand about composite indexes, I'll need:
CREATE INDEX INDEX01 ON MYTABLE (D, A)
CREATE INDEX INDEX02 ON MYTABLE (A, D, B)
CREATE INDEX INDEX03 ON MYTABLE (A, B, D, C)
CREATE INDEX INDEX04 ON MYTABLE (A, B, C, D)
(ID is the primary key column)
Is this correct?
I figure if I reorder the WHERE clauses, I can possibly make do with just one composite index:
SELECT DISTINCT A, COUNT(*) FROM MYTABLE
WHERE D IN ? AND A > ?
GROUP BY A ORDER BY A LIMIT 100
SELECT DISTINCT B, COUNT(*) FROM MYTABLE
WHERE D IN ? AND A = ? AND B > ?
GROUP BY B ORDER BY B LIMIT 100
SELECT DISTINCT C, COUNT(*) FROM MYTABLE
WHERE D IN ? AND A = ? AND B = ? AND C > ?
GROUP BY C ORDER BY C LIMIT 100
SELECT E, F, G, H FROM MYTABLE
WHERE D IN ? AND A = ? AND B = ? AND C = ? AND ID > ?
ORDER BY ID LIMIT 100
then I'll just need:
CREATE INDEX INDEX01 ON MYTABLE (D, A, B, C)
Is that correct?
However, I think that ordering the WHERE clauses this way would not be optimal. The reason for always trying to put the "IN" operation and the ">" operation as the last 2 WHERE clauses is:
MySQL would need to do more work for "IN" (compare with multiple values) as compared to "=", and possibly (due to my dataset and what I'm filtering), less rows will be pruned by this clause.
The ">" operation is mainly for pagination purposes. i.e. in certain cases, there will be little to no pruning due to this clause.
Is my understanding correct?