Andrey Sh
Andrey Sh

Reputation: 126

Should I begin a MySQL index with unique or non-unique field?

The problem I have is the following:

SELECT COUNT(*) 
FROM my_table 
WHERE another_id IN ( <about 100 values> ) 
AND state = ...

for different values of state.

How should the index look like? I was thinking about two options:

Is there any difference in performance between those two variants? Is there anything else to consider?

Edit: engine is InnoDB

Upvotes: 2

Views: 98

Answers (2)

Michael Shamis
Michael Shamis

Reputation: 1

I agree with the answer above. One clarification though is that you want to have ita hash index not btree index. It should work faster. The hash index wouldn't work well with any queries that involve inequality such as <=

Upvotes: 0

Bill Karwin
Bill Karwin

Reputation: 562260

For the query you show, you should create the index with state, another_id in that order.

Define the index with any columns referenced in equality conditions first, after them add one column referenced in a range condition or ORDER BY or GROUP BY.

You may also like my answer to Does Order of Fields of Multi-Column Index in MySQL Matter or my presentation How to Design Indexes, Really, or the video.

Upvotes: 1

Related Questions