I need some help figuring this out. I'm trying to get Mysql to use an index on a DATETIME field.
Mysql decides not to use the index if there's other (not used) fields in the table. Consider the two cases below:
A simple table with 2 fields works fine:
DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;
INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');
EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
| 1 | SIMPLE | datetime_index_test | range | created | created | 4 | NULL | 4 | Using where; Using index |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
A simple table with 3 fields, does not works fine:
DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
user int(10) unsigned DEFAULT 0,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;
INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');
EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | datetime_index_test | ALL | created | NULL | NULL | NULL | 8 | Using where |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
Finally, my question; Can anyone explain to me why Mysql decides not to use the index?