Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an index < or > MySQL queries?

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!)

like image 854
Tony Meyer Avatar asked Sep 24 '08 09:09

Tony Meyer


People also ask

Does MySQL use index for in query?

Introduction to MySQL indexesAn index is a data structure used to locate data without scanning all the rows in a table for a given query. Indexes help retrieve data faster. Indexes are not visible to the users. They help speed up queries that require a search.

Does indexing speed up queries?

What is Indexing? Indexing makes columns faster to query by creating pointers to where data is stored within a database. Imagine you want to find a piece of information that is within a large database. To get this information out of the database the computer will look through every row until it finds it.

What is the purpose of index in MySQL?

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs.

Does index work with in query?

The IN clause becomes an equality condition for each of the list and will use an index if appropriate.


2 Answers

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".
like image 123
MarkR Avatar answered Oct 13 '22 13:10

MarkR


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.

like image 20
Bruno De Fraine Avatar answered Oct 13 '22 13:10

Bruno De Fraine