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)?
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.
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.
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.
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 IN(1)
:
EXPLAIN
for a query with IN(1,2,3)
:
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. :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With