[Solved] Slow mysql delete query using IN statement
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Slow mysql delete query using IN statement

Database type:

I am doing a delete query which should run pretty much instantly

DELETE FROM
  TableA
WHERE
  TableA.SomeID IN (SELECT DISTINCT TableB.SomeID FROM TableB WHERE TableB.Something = Blah)

If I execute the query inside the IN statement on its own then it runs instantly. If I then comma separate the results of that and paste them into the outer query then that query runs instantly. However, when I run them together it takes 24 seconds. It's like the inner query is getting executed once per row. I also tried modifying it to use an EXISTS statement but that was also slow. Do I need to resort to a temp table for this?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `TableA` ADD INDEX `tablea_idx_someid` (`SomeID`);
ALTER TABLE `TableB` ADD INDEX `tableb_idx_something_blah` (`Something`,`Blah`);
The optimized query:
SELECT
        1 
    FROM
        TableA 
    WHERE
        TableA.SomeID IN (
            SELECT
                DISTINCT TableB.SomeID 
            FROM
                TableB 
            WHERE
                TableB.Something = TableB.Blah
        )

Related Articles



* original question posted on StackOverflow here.