Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of columns in a multi-column index in MySQL

I'm trying to understand what is better when defining multi-column indexes:

  • Putting the most selective column first (higher cardinality, for speed?); or
  • Putting the less selective column first (Lower cardinality, for index compression?)

Or maybe it depends if I'm optimizing for speed or space?

like image 762
sbargay Avatar asked Jan 23 '11 23:01

sbargay


People also ask

How important is the order of columns in indexes?

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.

How does index work on multiple columns?

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.

Does column order matter in MySQL?

Yes, column order does matter.

How are indexes ordered?

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.


2 Answers

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?

like image 189
FabianB Avatar answered Oct 06 '22 10:10

FabianB


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.

like image 43
RichardTheKiwi Avatar answered Oct 06 '22 09:10

RichardTheKiwi