views:

22

answers:

3

Dear all,

I have a set of large values that need to be compared in mysql.

May I know which is faster? For example:

Opt 1:
SELECT * FROM table WHERE v = 1 or v = 2 or v = 3 or v = 4 or... v = 100

Opt 2: 
SELECT * FROM table WHERE v IN (1,2,3,4,5,6,7,8,...,100)

May I know which option is faster for large value? Is there any better solution? Thank you.

+2  A: 

Are these all consecutive numbers? Then I would use

SELECT * FROM table WHERE v BETWEEN 1 AND 100
Frank
@frank. no, let's assume they are not consecutive.
benmsia
@benmsia Your example just suggested they are consecutive, and in this case a between is much faster than an enumeration 100 numbers, as the engine just has to do one range check instead of 100 comparisons.If there are gaps, then see the answer of OMG Ponies.
Frank
A: 

When I was studying databases my tutor told me that they effectively boil down to the same thing.

DrDipshit
Logically, yes they are equivalent. But the optimizers generally work better with IN vs OR.
OMG Ponies
Good point. I guess I was not talking specifically about speed at the time.
DrDipshit
+1  A: 

Assuming the numbers will not be consecutive, the IN clause is preferred for two reasons:

  1. More readable
  2. Optimized to run faster than OR statements.
OMG Ponies
The IN list is sorted so lookups can be done as a binary search. A bunch of OR's just evaluates each condition oneat a time until one matches: http://lists.mysql.com/mysql/216945
OMG Ponies