views:

529

answers:

4

If I have a query like "DELETE FROM table WHERE datetime_field < '2008-01-01 00:00:00'", does having the 'datetime_field' column indexed help? i.e. is the index only useful when using equality (or inequality) testing, or is it useful when doing an ordered comparison as well?

(Suggestions for better executing this query, without recreating the table, would also be ok!)

A: 

It does, check with a DESCRIBE SELECT FROM table ...

MattW.
+1  A: 

An index on the datetime field will definitely help with date range based searches. We use them all the time in our databases and the queries are rediculously slow without the indexes.

Jarod Elliott
+6  A: 

Maybe. In general, if there is such an index, it will use a range scan on that index if there is no "better" index on the query. However, if the optimiser decides that the range would end up being too big (i.e. include more than, say 1/3 of the rows), it probably won't use the index at all, as a table scan would be likely to be faster.

Use EXPLAIN (on a SELECT; you can't EXPLAIN a delete) to determine its decision in a specific case. This is likely to depend upon

  • How many rows there are in the table
  • What the range is that you're specifying
  • What else is specified in the WHERE clause. It won't use a range scan of one index if there is another index which "looks better".
MarkR
Perhaps this should be an additional question, but is there a simple answer (or reference to part of the MySQL documentation) that explains how the optimiser makes the decision about the range being too big? The specific case has nothing else in the WHERE.
Tony Meyer
+2  A: 

From MySQL Reference manual:

A B-tree index can be used for column comparisons in expressions that use the =, >, >=, <, <=, or BETWEEN operators.

For a large number of rows, it can be much faster to lookup the rows through a tree index than through a table scan. But as the other answers point out, use EXPLAIN to find out MySQL's decision.

Bruno De Fraine