2

I have a MySQL query where in the age is to checked against an array of possible-possible-values.

The query looks like :

select * from users where age in (15,18,20,22);

Some times, the ages-array might only have a single value, say [22].

In such circumstances, am wondering if the following query (A):

select * from users where age in (22);

will be optimum when compared to (B):

select * from users where age = 22;

Please, let me know your thoughts.

2
  • 2
    Compare the query plans.
    – Mat
    Commented Feb 7, 2012 at 14:37
  • Query plans appear to be the same when I try it on my DB here. MySQL is likely smart enough to figure out they're the same.
    – ceejayoz
    Commented Feb 7, 2012 at 14:39

4 Answers 4

6

As much i know IN clause is internally implemented as a series of where clauses like

WHERE id = 1 OR id = 2 OR id = 3

Please correct me if I am wrong...

0
1

I don't believe that there is any performance difference between IN and = operators in MySQL.

We use = operator when trying to compare a single element and when we have to compare list of elements we use IN clause.

Anyways, IN clause internally gets flatten as series of OR condition/OR'ed stack ... like

col1 IN('a','b','c')

Will become

col = 'a' OR col1 = 'b' OR col = 'c'
1

There shouldn't be a performance impact on using

... Id in (22)

Vs

... Id=22

The execution plan for both statements will be identical, the IN statement will be transformed to '=22' when the list in the IN only has one element.

0

You can use IN clause to replace many OR conditions. So

SELECT * FROM colA = 'Value1' or colA = 'Value2'

is the same as

SELECT * FROM colA IN ('Value1', 'Value2')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.