MySQL ORDER BY DESC is fast but ASC is very slow
Posted
by Pepper
on Stack Overflow
See other posts from Stack Overflow
or by Pepper
Published on 2010-05-22T01:29:40Z
Indexed on
2010/05/22
1:40 UTC
Read the original article
Hit count: 371
mysql
|Performance
Hello, I'm completely stumped on this one. For some reason when I sort this query by DESC it's super fast, but if sorted by ASC it's extremely slow.
This takes about 150 milliseconds:
SELECT posts.id
FROM posts USE INDEX (published)
WHERE posts.feed_id IN ( 4953,622,1,1852,4952,76,623,624,10 )
ORDER BY posts.published DESC
LIMIT 0, 50;
This takes about 32 seconds:
SELECT posts.id
FROM posts USE INDEX (published)
WHERE posts.feed_id IN ( 4953,622,1,1852,4952,76,623,624,10 )
ORDER BY posts.published ASC
LIMIT 0, 50;
The EXPLAIN is the same for both queries.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE posts index NULL published 5 NULL 50 Using where
I've tracked it down to "USE INDEX (published)". If I take that out it's the same performance both ways. But the EXPLAIN shows the query is less efficient overall.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE posts range feed_id feed_id 4 \N 759 Using where; Using filesort
And here's the table.
CREATE TABLE `posts` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`feed_id` int(11) NOT NULL,
`post_url` varchar(255) NOT NULL,
`title` varchar(255) NOT NULL,
`content` blob,
`author` varchar(255) DEFAULT NULL,
`published` int(12) DEFAULT NULL,
`updated` datetime NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `post_url` (`post_url`,`feed_id`),
KEY `feed_id` (`feed_id`),
KEY `published` (`published`)
) ENGINE=InnoDB AUTO_INCREMENT=196530 DEFAULT CHARSET=latin1;
Is there a fix for this? Thanks!
© Stack Overflow or respective owner