MySQL Forums
Forum List  »  Optimizer & Parser

index ignored
Posted by: Lauren Bradford
Date: May 18, 2006 12:00PM

hello. i've got a table that i have to run two queries against. one of them runs twice as fast as the other, even though they have the exact same WHERE clause. i ran an EXPLAIN on both of them and it turns out one is using the index and the other isn't. i'd like to figure out why, and also figure out how i can make the slower one faster.

CREATE TABLE `table1` (
`table1_id` int(11) unsigned NOT NULL auto_increment,
`col1` varchar(33) NOT NULL default '',
`col2` varchar(16) NOT NULL default '',
`col3` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`table1_id`),
KEY `idx_col2_col3` (`col3`,`col2`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

the first query is the slow one:

EXPLAIN SELECT COUNT(DISTINCT col1) AS total FROM table1 WHERE col2 = 'valuea' AND col3 >= DATE_SUB(NOW(), INTERVAL 1 DAY);
+----+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
| 1 | SIMPLE | table1 | ALL | idx_col2_col3 | NULL | NULL | NULL | 16176 | Using where |
+----+-------------+----------------+------+---------------+------+---------+------+-------+-------------+

as you can see, mysql chooses not to use the index. it also doesn't list Distinct in the extra colum with 'Using where,' and the type is 'ALL', rather than the 'range' i would expect. just to test things out, i took away the DISTINCT which made no difference. i then tried taking out the COUNT, and that didn't change things either. the next query is the quicker one:

EXPLAIN SELECT COUNT(*) AS total FROM table1 WHERE col2 = 'valuea' AND col3 >= DATE_SUB(NOW(), INTERVAL 1 DAY);
+----+-------------+----------------+-------+---------------+-------------+---------+------+-------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------+-------+---------------+-------------+---------+------+-------+--------------------------+
| 1 | SIMPLE | table1 | range | idx_col2_col3 | idx_col2_col3 | 24 | NULL | 15806 | Using where; Using index |
+----+-------------+----------------+-------+---------------+-------------+---------+------+-------+--------------------------+

any insight would be appreciated. thank you.

Options: ReplyQuote


Subject
Views
Written By
Posted
index ignored
2278
May 18, 2006 12:00PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.