So consider I have the following table:
table:
Assume I use queries that differ at runtime (a website for example where checkboxes denote whether or not to search on a specific field), some possible instances:
(Using some x, y, z for the values)
SELECT * FROM table WHERE c1 = 1 AND c2 = 2SELECT * FROM table WHERE c1 = 1 AND c2 = 2 AND c3 = x AND c4 = ySELECT * FROM table WHERE c1 = 2 AND c2 = 3SELECT * FROM table WHERE c1 = 2 AND c2 = 3 AND c5 = zThe questions:
(c1, c2, c3, c4, c5)? How will it be used in the several queries?MySQL documentation does a good job of explaining how multi-column indexes work here.
In general, the index can be used for a where clause when some number of column on the leftmost side of the index have equality conditions. Your where clauses use the following columns:
Any index starting with columns c1 and c2 would normally be used for these queries. MySQL can apply other conditions to using the index, such as selectivity. That is, if c1 and c2 have constant values (for instance) then using an index will not benefit the query.
To optimize all these combinations, you can create two indexes: c1, c2, c3, c4 and c2, c1, c5. The reason for swapping c1 and c2 in the second index is so you could handle queries where the condition is on c2 but not c1, as well as the reverse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With