Just a short introduction:
I have one table t1( id(mediumint), string(varchar(45) ) both belong to primary key.
I need to find in this table 5 strings, let’s say. And this table is like 5M + rows.
What would be faster?
-
One query using
IN():SELECT id, string FROM t1 WHERE string IN (value1,value2,...,value5)or
-
Five queries, one for each value:
SELECT id, string FROM t1 WHERE string = value1 SELECT id, string FROM t1 WHERE string = value2 ' ' SELECT id, string FROM t1 WHERE string = value5
The application server and database server will be on the same network (100Mbit or 1Gbit, not sure yet), not on the same machine.
Most of the time, using a single query is likely to be faster than using multiple queries, since it avoids the overhead of parsing, sending the queries and receiving multiple separate responses, and it allows for better optimization. When in doubt, profile.
Also keep in mind the length of the query. Most database servers have a limit of how long the query string can be. So, if you have long lists of values, you should send them in batches.