Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Performance - "IN" Clause vs. Equals (=) for a Single Value [duplicate]

This is a pretty simple question and I'm assuming the answer is "It doesn't matter" but I have to ask anyway...

I have a generic sql statement built in PHP:

$sql = 'SELECT * FROM `users` WHERE `id` IN(' . implode(', ', $object_ids) . ')'; 

Assuming prior validity checks ($object_ids is an array with at least 1 item and all numeric values), should I do the following instead?

if(count($object_ids) == 1) {     $sql = 'SELECT * FROM `users` WHERE `id` = ' . array_shift($object_ids); } else {     $sql = 'SELECT * FROM `users` WHERE `id` IN(' . implode(', ', $object_ids) . ')'; } 

Or is the overhead of checking count($object_ids) not worth what would be saved in the actual sql statement (if any at all)?

like image 503
JudRoman Avatar asked Mar 29 '12 13:03

JudRoman


People also ask

Is like faster than equals in SQL?

1 Answer. Using '=' operator is faster than the LIKE operator in comparing strings because '=' operator compares the entire string but the LIKE keyword compares by each character of the string.

Which operator is used for making a query shorter when there are too many values?

As you can see, the IN operator is much shorter and easier to read when you are testing for more than two or three values. You can also use NOT IN to exclude the rows in your list.

Which is more efficient SQL in or?

The best way to know is to profile both on your database with your specific data to see which is faster. So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.


2 Answers

Most of the other answers don't provide anything conclusive, just speculation. So, based on the good advice from @Namphibian's answer, I ran an EXPLAIN on some queries similar to the ones in the OP.

The results are below:


EXPLAIN for a query with = 1:

Explain for a query with <code>= 1</code>


EXPLAIN for a query with IN(1):

Explain for a query with <code>IN(1)</code>


EXPLAIN for a query with IN(1,2,3):

Explain for a query with <code>IN(1,2,3)</code>


As you can see, MySQL does optimize IN(1) to be the same as = 1 in this sort of query. @mes's answer seems to indicate that this might not always be the case with more complex queries, however.

So, for those who were too lazy to run the EXPLAIN themselves, now you know. And yes, you may want to run the EXPLAIN on your own query to be sure that it is handled this way. :-)

like image 100
J.D. Avatar answered Oct 17 '22 01:10

J.D.


There is no difference between the MySQL statements, and the MySQL optimiser will transform the IN to the = when IN is just one element. Don't bother.

like image 27
Konerak Avatar answered Oct 17 '22 00:10

Konerak