[Solved] Why MySQL doesn\'t use the index
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Why MySQL doesn\'t use the index

Database type:

I'm running these two different queries and I don't understand why on the first one sale table index is not used

EXPLAIN SELECT COUNT(`sale`.`saleId`) AS `nb`
FROM `sale` 
WHERE `sale`.`saleTransactionId` IN (
SELECT `transaction`.`transactionId`
FROM `transaction`  
WHERE `transaction`.`transactionId` = 87587
)

Result is

result 1 https://snag.gy/SusqF.jpg

Second one

EXPLAIN SELECT COUNT(`sale`.`saleId`) AS `nb`
FROM `sale` 
WHERE `sale`.`saleTransactionId` IN (87587)

Result is

result 2 https://snag.gy/ZgOXQ.jpg

Juste to be sure

SELECT `transaction`.`transactionId`
FROM `transaction`  
WHERE `transaction`.`transactionId` = 87587

returns juste one row

saleTransactionId is INT(11) as transactionId Both tables uses MyISAM

And sale index structure

sale index structure https://snag.gy/we3HL.jpg

Thanks!

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `transaction` ADD INDEX `transaction_idx_transactionid` (`transactionId`);
The optimized query:
SELECT
        `transaction`.`transactionId` 
    FROM
        `transaction` 
    WHERE
        `transaction`.`transactionId` = 87587

Related Articles



* original question posted on StackOverflow here.