1

If I have this index:

(col1, col2, col3)

I know it helps when I search through (col1); (col1, col2); (col1, col2, col3).

If I create another index with the exactly same columns, phpMyAdmin will warn me that one of those indexes may be removed, because they are the same.

However, if I have these indexes:

(col1, col2, col3)

(col1, col2)

(col1)

phpMyAdmin won't warn me at all.

So my question is, are the last two indexes necessary in any case? I think only the first index is enough.

Thank you.

3
  • 1
    The last 2 indexes are not necessary. Commented Aug 16, 2012 at 21:07
  • We don't know if they're necessary w/o seeing the table structure. If they are unique key or primary key or whatever, you can't delete them. Need more info to answer the 2nd part of the question. SHOW CREATE TABLE tablename\G Commented Aug 16, 2012 at 21:14
  • @randymelder - I'm not talking about UNIQUE or PRIMARY keys. I'm talking about common columns. I know that those you referred need to exist. Thank you. Commented Aug 16, 2012 at 21:17

1 Answer 1

3

MySQL will only use one index (the leftmost) to optimize the search. Quoting from the documentation:

"If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3)."

However, if any of the indexes are UNIQUE, then there's probably a good reason for them to be there.

If during your analysis you find that any of the columns are frequently used apart from one another, then you should consider adding separate indexes for each to optimize those queries.

E.g.

ALTER TABLE tablename ADD INDEX (col1), ADD INDEX (col2), ADD INDEX (col3);
Sign up to request clarification or add additional context in comments.

1 Comment

From your answer, I assume my point on the question is correct then. I know that I may have to create different indexes, where the leftmost prefix is different. The same for UNIQUE and PRIMARY. Thank you for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.