Alex Rivera | Logout

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

Asked 2012-03-29T13:33:44.833
46

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)?

Edit
Report

1 Answer

2

I imagine that internally mysql will treat the IN (6) query exactly as a = 6 query so there is no need to bother (this is called premature optimization by the way)

answered 2012-03-29T13:38:09.537

Your Answer