MySQL Subquery Optimization

Never use a subquery inside a WHERE field IN(…)  the SQL query.  It will slow down the process.

Slow:

SELECT * FORM table1 WHERE field1 IN
(SELECT field2 FROM table2 GROUP BY field1)

Instead of using a subquery inside an IN(…),  use INNER JOIN query. It will speed up the process, but in IN(…) query speed will slow exponentially as more rows are added.

Optimized:

SELECT * FROM table1 AS t1 INNER JOIN (
SELECT field2 FROM table2 GROUP BY field1
) AS t2 ON t1.field1=t2.field2;

Permanent link to this article: https://blog.openshell.in/2010/12/mysql-subquery-optimization/

Leave a Reply

Your email address will not be published.