Why does MySQL use 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;

Inquiry:

SELECT id, last_update
FROM newsletters
WHERE status = 1
ORDER BY last_update DESC 
LIMIT 0, 100
  • newsletters table has over 3 million records
  • takes more than 26 seconds to complete

Inquiry:

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 filesortand how is the request range?

+5
source share
1 answer

Used filesortto sort by last_update. You can avoid fileort by changing the index to status, last_update, so MySQL finds all rows with status 1 in the correct order.

For further optimization, change the index to status, last_update, id. This allows MySQL to satisfy the query simply by looking at the index, without searching the table.

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

All Articles