[Solved] MySQL Delete / Inner Join performance

EverSQL Database Performance Knowledge Base

MySQL Delete / Inner Join performance

Database type:

I have a MySQL database with ~27 million rows in one of its tables (analyses). I indexed two of the variables, time and ID, with the statements

ALTER TABLE `analyses` ADD INDEX(`time`);

Each statement took ~4 minutes. I then attempted to delete redundant rows, with the statement

DELETE a1 FROM analyses a1 INNER JOIN analyses a2 WHERE a1.log_id > a2.log_id 
AND a1.ID= a2.ID AND a1.time=a2.time;

This statement has been executing for ~2 days without an error.

  1. Is there a way I can estimate how long this statement should take?
  2. From what I understand, interrupting this process (ctrl-C or kill) would not corrupt the database; am I correct that it'd be safe to do so?
  3. Is there a way I could formulate the DELETE statement to increase execution speed, or should I just wait for this process to complete?

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 `analyses` ADD INDEX `analyses_idx_id_time_log_id` (`ID`,`time`,`log_id`);
The optimized query:
        analyses a1 
        analyses a2 
        a1.log_id > a2.log_id 
        AND a1.ID = a2.ID 
        AND a1.time = a2.time

Related Articles

* original question posted on StackOverflow here.