2

I have a table that contains 250 million records recording people who live in the US and their sate, county and settlement. A simplified version looks like:

mysql

I have put a combined index on surname, region, subregion and place. The following queries execute in exactly the same time:

SELECT SQL_NO_CACHE surname, place, count(*) as cnt FROM `ustest` group by place, surname;

SELECT SQL_NO_CACHE surname, region, count(*) as cnt FROM `ustest` group by region, surname;

I was under the impression that the first query would not use the index, as I thought that to use an index you had to query on all the columns from left to right.

Can anyone explain how MySQL uses indexes on multiple columns in such instances?

1
  • 1
    I would guess that in the lack of more specific indexes it uses your index with more dimension. I do not know, just an educated guess. Commented Jan 24, 2015 at 16:44

1 Answer 1

1

It's hard to tell the specifics of your queries' execution plans without seeing the EXPLAIN output.

But two things jump out:

  1. Both queries must take all rows in the table into account (you don't have a WHERE clause).
  2. Both queries could be satisfied by scanning your compound index based on surname being the lead column of that index. Because you're counting items, it's necessary to do a tight, not loose, index scan. (You can read about those.)

So it's possible that they both have the same execution plan.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Yes. The explain output for both is identical. I was just under the impression the index shouldn't be used.

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.