How to optimise MySQL queries based on EXPLAIN plan

Depends on what you’re going for and what the query is.

Generally, for every line in EXPLAIN that has a Using where, you need to have it using an index (possible keys and keys column). These are your filters and include WHERE and ON. Having it say Using index is even better. It means there’s a covering index, and MySQL can retrieve the data right from the index rather than visiting the row in the table data.

The lines where there is no Using where, and it is returning a large number of rows should be looked at. These are returning values for all rows in the table. I don’t know what your query is, so I don’t know whether to be alarmed here. Try filtering the result set to reduce the size and improve performance.

You generally should try to avoid seeing Using filesort or Using temporary, though those are only bad if you’re not expecting them.

Filesort usually appears with the ORDER clause. You generally want MySQL to use a covering index (Using index) so that the rows are returned already in order from the server. If they’re not, then MySQL must order them afterward, using filesort.

Using temporary can be bad when it refers to derived tables because they don’t have indexes. It seems that you’ve explicitly created a temporary table with indexes, so here, it’s not bad. Sometimes, your only choice is to use a derived table, and hence Using temporary.

Leave a Comment