Search code examples
mysqljoinquery-optimizationsql-deleteforce-index

MySQL ignoring Force Index for Delete Query, But Not For Equivalent Select Query


I am extremely confused and frustated here -

I have a table (table1) that is enormous.

I am trying to do a delete query based on another table. The query optimizer isn't using the appropriate index, so I am trying to force it

delete table1 
FROM table1
FORCE INDEX FOR JOIN (index1)  
inner JOIN table2  
where
table1.field1=table2.field1
and
table1.field2=table2.field2
and
date(table1.startdatetime)=table2.reportdate;

The equivalent select looks as follows:

SELECT * 
FROM table1
FORCE INDEX FOR JOIN (index1)  
inner JOIN table2  
where
table1.field1=table2.field1
and
table1.field2=table2.field2
and
date(table1.startdatetime)=table2.reportdate;

What I don't understand is that the delete query does not use the index, but the select query does

The "explain" from the select is:

1   SIMPLE  table2 index    idx1    idx1    55      1456    Using where; Using index
1   SIMPLE  table1 ref  index1 index1 51    table2.field1,table2.field2 508 **Using index condition**

But the explain for the delete is as follows:

# id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
1, SIMPLE, table2, index, idx1, idx1, 55, , 1456, Using where; Using index
1, SIMPLE, table1, ref, index1, index1, 51, table2.field1,table2.field2, 508, Using where

Why does the select statement have Using index condition and the equivalent delete have using where?

How can I force the delete to use the index also?

Thank you!


Solution

  • Index hints apply only to SELECT statements. (They are accepted by the parser for UPDATE statements but are ignored and have no effect.)

    from the official docs

    Even though it is not specifically called out, I'd assume DELETE falls under how UPDATE is handled, rather an SELECT.