Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL not using indexes; using filesort

MySQL appears to be not using indexes and is using filesort on the following query:

  SELECT `tweets`.* 
    FROM `tweets` 
   WHERE (`tweets`.contest_id = 159) 
ORDER BY tweet_id ASC, tweeted_at DESC LIMIT 100 OFFSET 0

I have indexes on contest_id, tweet_id and tweeted_at

When I execute EXPLAIN EXTENDED, Extra returns "Using where; using filesort". How can I improve my query?

like image 570
JZ. Avatar asked Jun 30 '11 23:06

JZ.


People also ask

Why index is not used in MySQL?

The Benefits and Drawbacks of Using Indexes in MySQLIndexes consume disk space. Indexes degrade the performance of INSERT, UPDATE and DELETE queries – when data is updated, the index needs to be updated together with it. MySQL does not protect you from using multiple types of indexes at the same time.

Does MySQL use index automatically?

Mostly we create index when creating table. Any column in creating table statement declared as PRIMARY KEY, KEY, UNIQUE or INDEX will be indexed automatically by MySQL. In addition, you can add indexes to the tables which has data.

What is using Filesort in MySQL?

In MySQL, filesort is the catch-all algorithm for producing sorted results for ORDER-BY or GROUP-BY queries. MySQL has two algorithms for filesort, both the original and the modified algorithms are described in the user manual.

Why MySQL does not pick correct index for few queries?

MySQL can only use an index for searches up to the first range. Removing the range requirement on log_type should improve performance, but you may get mixed results by adding it in later in an outer query. If you do this, you'll also have to remove log_type from the covering index.


1 Answers

When you mix ASC and DESC sorting, MySQL cannot use indexes to optimize the GROUP BY statement.

Also, using multiple keys to sort will result in it not being able to optimize the query with indexes.

From the docs:

http://dev.mysql.com/doc/refman/5.6/en/order-by-optimization.html

In some cases, MySQL cannot use indexes to resolve the ORDER BY, although it still uses indexes to find the rows that match the WHERE clause. These cases include the following:

You use ORDER BY on different keys:

SELECT * FROM t1 ORDER BY key1, key2;

...

You mix ASC and DESC:

SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;

If the two columns you are ordering on are not part of the same key, then you are doing both of the above things.

like image 113
Chris Laplante Avatar answered Oct 10 '22 04:10

Chris Laplante