Question

I have a query like

SELECT * FROM Table_name WHERE column1 = '1' AND  column2 IN ('1','2','3');

And index exists on (column1, column2, column3). Is my above query used index I have created or not? Basically I am confused with the IN keyword, without this it is using, but with IN I am not sure. Please explain me.

Was it helpful?

Solution 2

MySQL is capable of using indices with IN .. now, is MySQL using indices in the particular query? Well, ask the query planner!

In this case an index over (column1, column2, ..) could be used - because all the leftward components have been satisfied. That is, an index seek could be done on column1 (for =), and then column2 (for IN). But again, ask the query planner as unexpected plans are not unheard of; just because the query planner could choose an index doesn't mean that it will.

See EXPLAIN, for how to ask:

When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan. That is, MySQL explains how it would process the statement, including information [like index usage] about how tables are joined and in which order ..

.. With the help of EXPLAIN, you can see where you should add indexes to tables so that the statement executes faster by using indexes to find rows.

OTHER TIPS

MySQL can use indexes with IN conditions. If you only have an index on column2, it will most likely be used. If you have indexes on each of column1 and column2, only one of them can be used, and the query planner will have to decide which one seems better for a particular query. If you have a composite index on (column1, column2) then it should be able to use that index to match both columns in the WHERE clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top