6

I was wondering which of these would be faster (performance-wise) to query (on MySQL 5.x CentOS 5.x if this matters):

SELECT * FROM table_name WHERE id=1;
SELECT * FROM table_name WHERE id=2;
.
.
.
SELECT * FROM table_name WHERE id=50;

or...

SELECT * FROM table_name WHERE id IN (1,2,...,50);

I have around 50 ids to query for. I know usually DB connections are expensive, but I've seen the IN clause isn't so fast either [sometimes].

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137

5 Answers5

5

I'm pretty sure the second option gives you the best performance; one query, one result. You have to start looking for > 100 items before it may become an issue.

See also the accepted answer from here: MySQL "IN" operator performance on (large?) number of values

Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
3

IMHO you should try it and measure response time: IN should give you better performances...
Anyway if your ids are sequential you could try

SELECT * FROM table_name WHERE id BETWEEN 1 AND 50
Marco
  • 56,740
  • 14
  • 129
  • 152
0

Here is another post where the discuss the performance of using OR vs IN. IN vs OR in the SQL WHERE Clause

You suggested using multiple queries, but using OR would also work.

Community
  • 1
  • 1
marteljn
  • 6,446
  • 3
  • 30
  • 43
0

2nd will be faster because resources are consumed when query gets interpreted and during php communication with mysql for sending query and waiting for result , if your data is sequential you can also do just

   SELECT * FROM table_name WHERE id <= 50;
Mr Coder
  • 8,169
  • 5
  • 45
  • 74
0

I was researching this after experimenting with 3000+ values in an IN clause. It turned out to be multitudes faster than individual SELECTs since the column referenced in the IN was not keyed. My guess is that in my case it only needed to build a temporary index for that column once instead of 3000 separate times.

sreimer
  • 4,913
  • 2
  • 33
  • 43