I'm trying to understand what is better when defining multi-column indexes:
Or maybe it depends if I'm optimizing for speed or space?
Indexes can be composites - composed of multiple columns - and the order is important because of the leftmost principle. Reason is, that the database checks the list from left to right, and has to find a corresponding column reference matching the order defined.
If you specify the columns in the right order in the index definition, a single composite index can speed up several kinds of queries on the same table. A multiple-column index can be considered a sorted array, the rows of which contain values that are created by concatenating the values of the indexed columns.
Yes, column order does matter.
The ordering of a two-column index is therefore like the ordering of a telephone directory: it is first sorted by surname, then by first name. That means that a two-column index does not support searching on the second column alone; that would be like searching a telephone directory by first name.
The order of the columns should match the order in which the columns are queried later or MySQL will not use them. This is the question you should really think about.
Read more here.
UPDATE:
For your question about cardinality maybe read this. Is this similar to your question? Does it answer it?
Always put the most selective column in the beginning, there is very rarely a reason for the other way around.
or maybe it depends if I'm optimizing for speed or space?
Let me put it this way. What is the point of using less storage, if it causes the index not to be used at all
? A low cardinality index (going in column order) will normally not be used if it is not a covering index for the query, because it will be terribly expensive to go back to the data for other columns.
The point of indexes is to assist the query and having them in the right order (cardinality) should always be the first and foremost consideration.
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