[TiDB Usage Environment] Production Environment
[TiDB Version] v4.0.9
[Reproduction Path] MySQL client
[Encountered Problem: Phenomenon and Impact]
The same query statement, with the same WHERE condition (different values), sometimes uses an index (IndexLookup) and sometimes performs a table scan (TableReader).
[Resource Configuration]
[Attachment: Screenshot/Log/Monitoring]
The actual execution plan may not be the one shown. You can check if there is this SQL in the slow SQL records to see the related execution plan. You can also use the explain analyze method to see what the execution plan looks like.
Currently, it is a composite index (bucketname, name, version).
So how should this issue be explained? And how can it be resolved or worked around? Modifying the index in a production environment is not very feasible.
Hello, why does the same where condition cause selectivity issues? What is the reason for this??? Clearly, the where condition matches the first two columns of the composite index.
This is generally caused by inaccurate statistics, histograms, and severe column skew. As mentioned by the expert above, the order of your index should be better like this: name, bucketname. You can create a new index and leave the original one unchanged for now.
I think if the values in the name field of your table are mostly different, you don’t need a composite index. Just create an index on the name field directly. If inaccurate statistics prevent the index from being used, you can directly specify it with a hint, like use_index.
I think it might be due to the cost of querying the two SQLs, because the optimizer ultimately decides how to query based on the cost of the two queries. You can check the cost of both.