user_78361084
user_78361084

Reputation: 3908

Why won't my query use the index on my datetime field?

I have the following table:

CREATE TABLE 'tableA'(
 `col1` int(11) NOT NULL AUTO_INCREMENT,
  `col2` varchar(20) NOT NULL,
  `col3` int(11) NOT NULL,
  `col4` varchar(200) NOT NULL,
  `col5` varchar(15) NOT NULL,
  `col6` datetime NOT NULL,
  PRIMARY KEY (`col1`),
  UNIQUE KEY `col2,col3` (`col2`,`col3`),
  KEY `col6` (`col6`)
) ENGINE=InnoDB AUTO_INCREMENT=1881208 DEFAULT CHARSET=utf8

I have an index on col6, a datetime column. I have almost 2M rows in the table, and the dates range from 1/1/2007 to 11/27/2012.

When I run the following, it doesn't use my index:

EXPLAIN SELECT * FROM tableA ORDER BY col6 ASC


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

I tried converting the datetime field to an integer and converting the datetime to a unix timestamp. However, it still won't use my index. What am I missing? Why does the optimizer insist on sorting through lots of rows (in this case 1,933,765 rows) rather than use the index?

Upvotes: 6

Views: 202

Answers (1)

Ray
Ray

Reputation: 41428

Since you are not selecting on anything based on the index to narrow the result set, using it would only incur additional work to lookup via point-lookup every each row in the primary table.

Upvotes: 4

Related Questions