I've got a simple query:
SELECT distinct state FROM customers WHERE country = 'us'
The idea is to get a list of states in the US that customers live in.
I've got around 800k rows, and an index on state
and on country
. This query takes about 4s to run, which is way too long, as this needs to be in real time.
If I remove the WHERE
clause, it figures it out almost instantly. I looked into why, and when I run an explain
on the query with the WHERE clause, it does not use the state
index. When I get rid of the WHERE clause, it starts using the state index again. Why is this happening, and is there a way I can make it use both indexes?
I've browsed other questions on SO that seem similar, but it seems like for the ones I found, they were very complicated queries, and the solution was just a query rewrite. This is so simple, though, I think it gets to the heart of the problem.
Update:
I have found that if I do an index on us_state
, it works in about .5s, which is good enough. I'd like to have multiple parts to the WHERE
clause at some point, though, so making a compound index for all the parts is still not optimal. As such, I leave this question open looking for a better solution.
CreateTable
CREATE TABLE `customers` (
`country` varchar(5) DEFAULT NULL,
`st` varchar(50) DEFAULT NULL,
KEY `state` (`state`),
KEY `country` (`country`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1