Link to home
Start Free TrialLog in
Avatar of dirknibleck
dirknibleck

asked on

MySQL index on date fields question

I'd like to know if I can improve what I've done so that it works, or if MySQL just doesn't operate on date indexes in the way I understood.

I have a table of thousands of records which I need to filter based on a date range (i.e. pull every record between two dates). I've created the table, and I have an index on the date field. However, when I run the query below against the table, it does not seem to be using the index.

Below is the Table structure and the query. Attached is the result of the Explain.
CREATE TABLE `games_copy` (
  `table_id` int(11) NOT NULL AUTO_INCREMENT,
  `start_date` datetime DEFAULT NULL,
  `end_date` datetime DEFAULT NULL,
  PRIMARY KEY (`table_id`),
  KEY `start_date_2` (`start_date`,`end_date`),
  KEY `start_date` (`start_date`)
) ENGINE=MyISAM AUTO_INCREMENT=7221 DEFAULT CHARSET=latin1;


SELECT * FROM games_copy WHERE start_date >= '2011-09-01' AND start_date <= '2012-08-31'

explain SELECT * FROM games_copy WHERE start_date >= '2011-09-01' AND start_date <= '2012-08-31'

Open in new window

explain-query.csv
Avatar of Nem Schlecht
Nem Schlecht
Flag of United States of America image

I'm a little confused... your EXPLAIN query states that it'll use the 'start_date_2' and 'start_date' indexes.

I generated 100K rows of random dates in 2011 and 2012, inserted them into your same table, ran your query, and it returned almost 40K rows of results in .2 seconds on my machine.

Have you done a lot of DELETEs on this table?  If so, it might be a little fragmented, so running "ANALYZE TABLE games_copy" will help it a little bit, but otherwise everything looks good here.
Avatar of dirknibleck
dirknibleck

ASKER

Am I misreading the Explain output? start_date_2 and start_date are listed under possible keys, however there is nothing listed in the Key column. My understanding was that this meant it found two keys available, but it didn't use any of them.
ASKER CERTIFIED SOLUTION
Avatar of Nem Schlecht
Nem Schlecht
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial