Skip to content
Advertisement

How to optimize MySQL select query or make it faster

I have a select query, that selects over 50k records from MySQL 5.5 database at once, and this amount is expected to grow. The query contains multiple subquery which is taking over 120s to execute.

Initially some of the sale_items and stock tables didn’t have more that the ID keys, so I added some more:

This is the explain result

I am expecting that the query takes less that 3s at most, but I can’t seem to figure out the best way to optimize this query.

Advertisement

Answer

The query looks fine to me. You select all data and aggregate some of it. This takes time. Your explain plan shows there are indexes on the IDs, which is good. And at a first glance there is not much we seem to be able to do here…

What you can do, though, is provide covering indexes, i.e. indexes that contain all columns you need from a table, so the data can be taken from the index directly.

This can really boost your query.

What you can try About the query itself is to move the subqueries to the FROM clause. MySQL’s optimizer is not great, so although it should get the same execution plan, it may well be that it favors the FROM clause.

(If sale_id is unique in refunds, then you can even join it to sale_items. Again: this should usually not make a difference, but in MySQL it may still. MySQL was once notorious for treating IN clauses much worse than the FROM clause. This may not be the case anymore, I don’t know. You can try – if refunds.sale_id is unique).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement