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.
Very interesting read.
Thank you.
Historically (ie, I haven’t checked recently if true) given a set of available indexes, MySQL would use the index which is represented by the lowest bit in the index bitmask and MySQL is only able to choose from about 60 indexes, max.
The primary index is always the first index (first bit). The remaining indexes are sorted in order of uniqueness and length. This index ordering is done at the table creation time.
Which reminds me … for a storage engine that I wrote for a past employer about 10 years ago, I had implemented a form of table discovery in MySQL which index 0 (usually primary key) was actually the recid … and the remaining keys were in the order used by the native database. Since the recid was not a user-visible column, it was not generally possible to use it in a query. (I later implemented hacks to make it a virtual column which didn’t show up on SHOW CREATE etc but it was not recommended to use because a rows recid can change when the row is modified).
MySQL wrote out the frm files from the discovered tables without the use of the upper parsing/sorting layers of MySQL and so I was free to format the table layout however I liked, including having ‘spare’ space in the record and having ‘overlap’ fields.
It worked very well. Fun times.
Your logic in Solution#1…. the statistics the InnoDB subsystem and the optimiser has don’t know about fragmentation, so it won’t affect the choice of execution method.
Arjen,
Thanks. You are right, I didn’t even mean defragmentation. I’ve corrected the text.
@shlomi ye of course it’ll update the stats, but OPTIMIZE TABLE is a very costly way of accomplishing that. As you noted, it’ll lock the table for reads as well as writes for the duration as it’s rewriting the entire table.
To just update the stats, ANALYZE TABLE is the way to go, that was your method#2. the issue there is that InnoDB just takes a few index dives, so it can be a) statistically wrong and b) it has a higher chance of being wrong with a bigger dataset, as the # of dives is a constant. I think there’s a Google or Percona patch to modify the # of dives (server-global), that can be useful when you know you have a big(ger) dataset.