For sql like select * from table where fieldA in (...)
, if there are lots of values in parentheses(like 1000 values), and there is a B-tree index on fieldA. How mysql execute this sql.
Does it work like foreach(value in values) {select * from table where fieldA=value}
, or it has some better way to do it
In this question Is SQL IN bad for performance?. It only says IN predicate is translated into OR predicate. It doesn’t tell me what is the execution plan.
2
Answers
It depends on the size of the table and values in it. It could be a "full table scan", usually when the number of selected values is rather close to the size of the table or the number of values is very high. Or the index could be used. It really depends on the production data within the table.
See next experiment.
1.Create table (about 1250 rows) – significant for test.With this size
Index seek
better thenfull table scan
2.Run query with IN(…) without{"query_cost": "125.35"} and with index {"query_cost": "19.41"}.
3.See difference. Query with index is faster than without.
Will the DBMS deploy the condition IN(…) in the sequence (… or … or …), or use the index and JOIN, or some other optimization, depends significantly on the availability of indexes and other properties of the database.
Test query
Some data about query without index
With index
Fiddle