This is the table I have:
CREATE TABLE `person` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `age` (`age`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=latin1;
This is the output of explain:
mysql> explain select * from person order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 10367
Extra: Using filesort
1 row in set (0.00 sec)
What’s going on? Why isn’t MySQL using the age index to do the sorting? I tried doind analyze table, but it didn’t make any difference.
Just for reference, here’s the distribution of data in the table:
mysql> select age, count(*) from person group by age;
+-----+----------+
| age | count(*) |
+-----+----------+
| 21 | 1250 |
| 22 | 1216 |
| 23 | 1278 |
| 24 | 1262 |
| 25 | 1263 |
| 26 | 1221 |
| 27 | 1239 |
| 28 | 1270 |
+-----+----------+
8 rows in set (0.04 sec)
UPDATE
@grisha seems to think that you can’t select a field not in the index. That doesn’t seem to make any sense, however, it looks like the following works:
mysql> explain select age from person order by age \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: age
key_len: 4
ref: NULL
rows: 10367
Extra: Using index
1 row in set (0.00 sec)
And also if I add an index that covers all the field it works as well:
mysql> alter table person add key `idx1` (`age`, `id`, `name`);
Query OK, 0 rows affected (0.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> explain select * from person order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: idx1
key_len: 35
ref: NULL
rows: 10367
Extra: Using index
1 row in set (0.00 sec)
@eggyal suggested using index hints. This seems to work as well, and is probably the correct answer:
mysql> explain select * from person force key for order by (age) order by age\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: person
type: index
possible_keys: NULL
key: age
key_len: 4
ref: NULL
rows: 10367
Extra:
1 row in set (0.02 sec)
Index can help you in sorting, when you select only index column. In your case you select
*, thereforemysqldoesn’t use index.Why usually index can’t help in sorting ?
If we want to sort some table
tby fieldmy_fieldusing index onmy_field, we will do :Assuming not clustered index, the above will execute as many random I/O’s as the number of rows in t(might be huge), whereas simple external sorting algorithm will read the data by blocks/pages sequentially and will execute much less random I/O’s.
So, of course you can say to db : “I want to do sorting using index”, but it’s really not efficient.