[Solved] How to optimize this delete query?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

How to optimize this delete query?

I am trying to run this query:

delete FROM `customer` where customer_id 
not in (SELECT distinct customer_id FROM `order`);

But it's taking a long time, leading to timout and breaks in middle because customer table has more than a million records.

How can I make it fast? any alternative?

edit

Here is EXPLAIN of same with SELECT:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   PRIMARY     customer    index   NULL    PRIMARY     4   NULL    127659  Using where; Using index
2   DEPENDENT SUBQUERY  order   ALL     NULL    NULL    NULL    NULL    25141   Using where

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 `customer` ADD INDEX `customer_idx_customer_id` (`customer_id`);
The optimized query:
SELECT
        1 
    FROM
        `customer` 
    WHERE
        `customer`.customer_id NOT IN (
            SELECT
                DISTINCT `order`.customer_id 
            FROM
                `order`
        )

Related Articles



* original question posted on StackOverflow here.