Yes, the index will help you when using ORDER BY. Because INDEX is a sorted data structure, the query will be faster.
Take a look at this example: table test2 with 3 rows. I used LIMIT after ordering to show the difference in execution.
DROP TABLE IF EXISTS `test2`; CREATE TABLE `test2` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `value` varchar(10) CHARACTER SET utf8 COLLATE utf8_swedish_ci NOT NULL, PRIMARY KEY (`id`), KEY `ix_value` (`value`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
MySQL checked 3 lines to output the result. After CREATE INDEX we get the following:
mysql> CREATE INDEX ix_value ON test2 (value) USING BTREE; Query OK, 0 rows affected (0.14 sec) -- ---------------------------- -- With INDEX -- ---------------------------- mysql> EXPLAIN SELECT * FROM test2 ORDER BY value LIMIT 1\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test2 type: index possible_keys: NULL key: ix_value key_len: 32 ref: NULL rows: 1 Extra: Using index 1 row in set (0.00 sec)
Now MySQL uses only 1 row.
Responding to the comments I received, I tried the same query without LIMIT:
-- ---------------------------- -- Without INDEX -- ---------------------------- mysql> EXPLAIN SELECT * FROM test2 ORDER BY value\G *************************** 1. row ****************** id: 1 select_type: SIMPLE table: test2 type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 3 Extra: Using filesort -- ---------------------------- -- With INDEX -- ---------------------------- mysql> EXPLAIN SELECT * FROM test2 ORDER BY value\G *************************** 1. row ***************** id: 1 select_type: SIMPLE table: test2 type: index possible_keys: NULL key: ix_value key_len: 32 ref: NULL rows: 3 Extra: Using index
As we can see, it uses the index for the 2nd ORDER BY .
To create an index in your field, use this:
CREATE INDEX ix_comment_time ON tbl_comments (comment_time) USING BTREE;
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
user4035
source share