Reputation: 579
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.
Upvotes: 1
Views: 3168
Reputation: 63442
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.
Upvotes: 5
Reputation: 3353
The only time when having multiple queries will be faster and more efficient is when you need complex and possibly multiple JOINs in your queries, than it is better to get separate results from separate tables and JOIN them in memory in your application. Mainly as a way of saving transfer time/bandwidth.
Every other time it is best to run single query.
Upvotes: 1
Reputation: 17610
One query using the IN() should be faster. Make sure you have an index with "string" as the first column.
Upvotes: 2