4

I have a table

CREATE TABLE `pd` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `language_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `meta_description` varchar(255) NOT NULL,
  `meta_keyword` varchar(255) NOT NULL,
  `seo_title` varchar(255) NOT NULL,
  `seo_h1` varchar(255) NOT NULL,
  PRIMARY KEY (`product_id`,`language_id`),
  KEY `language_id` (`description`(128),`language_id`),
  KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=47019 DEFAULT CHARSET=utf8;

When I run this query

EXPLAIN SELECT * FROM `pd` ORDER BY product_id;

I get this result:

+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows   | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
|  1 | SIMPLE      | pd    | index | NULL          | PRIMARY | 8       | NULL | 139551 |       |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+

When I run this query

EXPLAIN SELECT * FROM `pd` ORDER BY name;

I get this result:

+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra          |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+
|  1 | SIMPLE      | pd    | ALL  | NULL          | NULL | NULL    | NULL | 137762 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+

Why in second case index isn't used? Only difference I see is product_id is part of primary key and name is non-unique index.

2
  • The fact that product_id is an int (fixed width type) and name is a varchar (variable width type) is a pretty big difference. Commented Dec 1, 2013 at 9:52
  • @vangelion: and what is that difference? In the index the prefix for varchar is stored anyway. M? Commented Dec 1, 2013 at 9:52

1 Answer 1

1

As soon as the name isn't a clustered key - it will be much more expensive to read the index first and seek for every row one by one in data.

So mysql (and I think that any other would DBMS) decdies to read the data and sort it in-memory.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.