Question

Using MySQL version 5.5.28,

I have a table defined as such:

CREATE TABLE IF NOT EXISTS `groups` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `desc` text NOT NULL,
  `permissions` varchar(80) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

As you can see, it's pretty simple. I have a primary key on the id field. Now, I query against it using something like this:

SELECT permissions FROM groups WHERE id IN ('9', '8', '6','14','11','7','5');

Unfortunately it refuses to use the key, and it shows up in my slow query log.

Performing EXPLAIN on it provides:

mysql> EXPLAIN SELECT permissions FROM groups WHERE id IN ('9', '8', '6','14','11','7','5');
+----+-------------+--------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+--------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | groups | ALL  | PRIMARY       | NULL | NULL    | NULL |   16 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)

It only has less than 20 rows in the entire table, so I get why it wouldn't likely use the index. But, why would this be a "slow query" for MySQL?

Was it helpful?

Solution

With a small number of rows, full scan will almost always be the fastest way to access the table. Also, selectivity important - even if id is unique, the query returns around 30% of all rows (assuming you have 20). It appears in slow query log not because it's slow, but because it doesn't use index (it should be an option to control that behaviour, I just don't remember it from the top of my head)

Update I just double checked, option is log-queries-not-using-indexes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top