HyderA
HyderA

Reputation: 21381

Why is MySQL using filesort in this case?

Table Structure:

CREATE TABLE IF NOT EXISTS `newsletters` 
(
    `id` int(11) NOT NULL auto_increment,
    `last_update` int(11) default NULL,
    `status` int(11) default '0',
    `message_id` varchar(255) default NULL,
    PRIMARY KEY  (`id`),
    KEY `status` (`status`),
    KEY `message_id` (`message_id`),
    KEY `last_update` (`last_update`)
) 
ENGINE=MyISAM DEFAULT CHARSET=latin1;

The Query:

SELECT id, last_update
FROM newsletters
WHERE status = 1
ORDER BY last_update DESC 
LIMIT 0, 100

Query explain:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  newsletters range   status  status  5   NULL    3043354 Using where; Using filesort

So why is it not using filesort, and how is it a range query?

Upvotes: 5

Views: 1657

Answers (1)

Andomar
Andomar

Reputation: 238116

It's using filesort to sort on last_update. You can avoid the filesort that by changing the index to status, last_update, so MySQL finds all rows with status 1 in the right order.

To further optimize, change the index to status, last_update, id. That allows MySQL to satisfy the query just by looking at the index, without a table lookup.

CREATE INDEX idx_newsletters_status
ON newsletters(status, last_update, id);

Upvotes: 5

Related Questions