Why won't MySQL use my index?

2019-09-08 22:50发布

问题:

If I have the following table:

CREATE TABLE `mytable` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(64) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_first_letter` (`name`(1)),
  KEY `name_all` (`name`)
)

Will MySQL ever choose to use the name_first_letter index over the name_all index? If so, under what conditions would this happen?

I have done some quick tests and I'm not sure if MySQL will choose the name_first_letter index even when using index hints:

-- This uses name_all
EXPLAIN SELECT name FROM mytable
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';

-- This uses no index at all
EXPLAIN SELECT name FROM mytable USE INDEX (name_first_letter)
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';

Can any MySQL gurus shed some light on this? Is there even a point to having name_first_letter on this column?

Edit: Question title wasn't quite right.

回答1:

It will not make sense to use the index for your query, because you are selecting the full name column. That means that MySQL cannot use the index alone to satisfy the query.

Further, I believe that MySQL cannot understand that the SUBSTRING(name FROM 1 FOR 1) expression is equivalent to the index.

MySQL might, however, use the index if the index alone can satisfy the query. For example:

select count(*)
  from mytable
 where name like 'T%';

But even that depends on you statistics (hinting should work).

MySQLs partial index feature is intended to save space. It does (usually) not make sense to have both, the partial and the full column index. You would typically drop the shorter one. There might be a rare case where it makes sense, but doesn't make sense in general.