Sometimes MySQL gets it wrong. It doesn’t use the right index.
It happens that MySQL generates a query plan which is really bad (EXPLAIN says it’s going to explore some 10,000,000 rows), when another plan (soon to show how was generated) says: “Sure, I can do that with 100 rows using a key”.
A true story
A customer had issues with his database. Queries were taking 15 minutes to complete, and the db in general was not responsive. Looking at the slow query log, I found the criminal query. Allow me to bring you up to speed:
A table is defined like this:
CREATE TABLE t ( id INT UNSIGNED AUTO_INCREMENT, type INT UNSIGNED, level TINYINT unsigned, ... PRIMARY KEY(id), KEY `type` (type) ) ENGINE=InnoDB;
The offending query was this:
SELECT id FROM data WHERE type=12345 AND level > 3 ORDER BY id
The facts were:
- `t` has about 10,000,000 rows.
- The index on `type` is selective: about 100 rows per value on average.
- The query took a long time to complete.
- EXPLAIN has shown that MySQL uses the PRIMARY KEY, hence searches 10,000,000 rows, filtered “using where”.
- The other EXPLAIN has shown that by using the `type` key, only 110 rows are expected, to be filtered “using where”, then sorted “using filesort”
So MySQL acknowledged it was generating the wrong plan. The other plan was better by its own standards.
Solving the problem
Let’s walk through 7 ways to solve the problem, starting with the more aggressive solutions, refining to achieve desired behavior through subtle changes.
Solution #1: OPTIMIZE
If MySQL got it wrong, it may be because the table was frequently changed. This affects the statistics. If we can spare the time (table is locked during that time), we could help out by rebuilding the table.
Solution #2: ANALYZE
ANALYZE TABLE is less time consuming, in particular on InnoDB, where it is barely noticed. An ANALYZE will update the index statistics and help out in generating better query plans.
But hold on, the above two solutions are fine, but in the given case, MySQL already acknowledges better plans are at hand. The fact was I tried to run ANALYZE a few times, to no avail.
Solution #3: USE INDEX
Since the issue was urgent, my first thought went for the ultimate weapon:
SELECT id FROM data USE INDEX(type) WHERE type=12345 AND level > 3 ORDER BY id
This instructs MySQL to only consider the indexes listed; in our example, I only want MySQL to consider using the `type` index. It is using this method that generated the other (good) EXPLAIN result. I could have gone even more ruthless and ask for FORCE INDEX.
Solution #4: IGNORE INDEX
A similar approach would be to explicitly negate the use of the PRIMARY KEY, like this:
SELECT id FROM data IGNORE INDEX(PRIMARY) WHERE type=12345 AND level > 3 ORDER BY id
A moment of thinking
The above solutions are “ugly”, in the sense that this is not standard SQL. It’s too MySQL specific.
I’ve asked the programmers to do a quick rewrite, and had a few moments to consider: why did MySQL insist on using the PRIMARY KEY. Was it because I’ve asked it for the `id` column only? I rewrote as follows:
SELECT id, type, level FROM data WHERE type=12345 AND level > 3 ORDER BY id
Nope. EXPLAIN got me the same bad plan. Then it must be the ORDER BY clause:
SELECT id FROM data WHERE type=12345 AND level > 3
Sure enough, EXPLAIN now indicates using the `type` index, only reading 110 rows. So MySQL preferred to scan 10,000,000 rows, just so that the rows are generated in the right ORDER, and so no sorting is required, when it could have read 110 rows (where each row is a mere INT) and sort them in no time.
Armed with this knowledge, a few more options come at hand.
Solution #5:Move some logic to the application
At about that point I got a message that the programmers were unable to add the USE INDEX part. Why? They were using the EJB framework, which limits your SQL-like queries to something very generic. Well, you can always drop the ORDER BY part and sort on the application side. That isn’t fun, but it’s been done.
Solution #6: Negate use of PRIMARY KEY
Can we force MySQL to use the `type` index, retain the ORDER BY, and do it all with standard SQL? Sure. The following query does this:
SELECT id, type, level FROM data WHERE type=12345 AND level > 3 ORDER BY id+0
id+0 is a function on the `id` column. This makes MySQL unable to utilize the PRIMARY KEY (or any other index on `id`, had there been one).
In his book “SQL Tuning“, Dan Tow dedicates a chapter on hints and tips like the above. He shows how to control the use or non-use of indexes, the order by which subqueries are calculated, and more.
Unfortunately, the EJB specification said this was not allowed. You could not ORDER BY a fucntion. Only on normal column.
Solution #7: Make MySQL think the problem is harder than it really is
Almost out of options. Just a moment before settling for sorting on the application side, another issue can be considered: since MySQL was fooled once, can it be fooled again to make things right? Can we fool it to believe that the PRIMARY KEY would not be worthwhile to use? The following query does this:
SELECT id, type, level FROM data WHERE type=12345 AND level > 3 ORDER BY id, type, level
Let’s reflect on this one. What is the order by which the rows are returned now? Answer: exactly as before. Since `id` is PRIMARY KEY, it is also UNIQUE, so no two `id` values are the same. Therefore, the secondary sorting column is redudant, and so is the following one. We get exactly the same result as “ORDER BY id”.
But MySQL didn’t catch this. This query caused MySQL to say: “Mmmmm. ‘ORDER BY id, type, level’ is not doable with the PRIMARY KEY only. Well, in this case, I had better used the `type` index”. Is this a weakness of MySQL? I guess so. Maybe it will be fixed in the future. But this was the fix that made the day.
[Translated from Persian via Google translate]
Good day.
I think I’m the problem here
I have a table with a varchar field with 4 1000000 Record
The index for all fields I
But when running the query with a long pause (20) seconds to get across.
This pause when sorting (order by) more!
I did not see any difference in the index itself was removed
Index seems to have no effect.
Please Please Help
please use http://translate.google.com. persian to english
@pirani, I’m sorry. I can’t possibly understand the question. My advice is to uploadyour question to StackOverflow, or else get decent consulting.
Option #7 indeed helped, I was going nuts as to why MySQL suddenly stopped using index – might be due to fragmentation.
Adding order by column forced optimizer to use the correct Index.
Thank You very much for the article.
According to my “true story” as You wrote, I’ll add option#8. In my case there were two big tables with 50 fields. Yes such amount is madness, but we have to do so, because a searching in one table was much more faster then joining of nearby 35 tables with indexes. So, in one table indexes was working fine, but in another the indexes refused to work. I spent over 12 hours to optimize a query in the second table, according to all advices over the internet. They did not bring results! I was ready to surrender, but in the last moment I found the error during the designing of these tables. First table engine was innoDB – indexes works fine, but the second was myIsam. After rebuilding the second table to InnoDB – indexes started to work. I tried to find out the reason of it in manuals – but couldn’t! But I think the reason is in table engine properties as for indexes and keys. They are different.
Best regards!
Well documented article Shlomi!
What could have also helped is if you had mentioned the Exec Time for each of the Solutions#.
It would have helped with the comparisons. But nevertheless, this gives us techniques which can put to practice.