Reputation: 29413
I have a problem where my query is Using filesort
, even though the field is indexed.
This is my query:
EXPLAIN
SELECT u.name, u.surname, u.id
FROM rw_users u
ORDER BY u.created DESC
LIMIT 4
This is the output:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE u ALL 9 Using filesort
This is create table
:
CREATE TABLE `rw_users` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`created` int(11) unsigned NOT NULL,
`email` varchar(255) COLLATE utf8_swedish_ci NOT NULL,
`password` char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`name` varchar(100) COLLATE utf8_swedish_ci NOT NULL,
`surname` varchar(100) COLLATE utf8_swedish_ci NOT NULL,
`premium` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT 'level or premium membership (0 = standard)',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
KEY `password` (`password`),
KEY `created` (`created`),
KEY `premuim` (`premium`),
KEY `name_surname` (`name`,`surname`),
CONSTRAINT `FK_rw_users` FOREIGN KEY (`premium`) REFERENCES `rw_premium` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci
What do I need to do to get rid of Using filesort
? I tested on database (exactly the same table) with 118 rows and it still gives me Using filesort
, so it can't use it because its faster than using index.
Upvotes: 0
Views: 237
Reputation: 29101
For the best performance for select queries add covering index. See here:
ALTER TABLE rw_users ADD KEY ix1 (created, name, surname, id);
for INNODB
engine you don't need to include id
in index, check both indexes with EXPLAIN
.
ALTER TABLE rw_users ADD KEY ix1 (created, name, surname);
Upvotes: 2