Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query optimization: IN() vs OR

I've been reading, that MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?

Which approach is better? Is there a performance difference?

1

SELECT *
FORM `somewhere`
WHERE 
  `id` = 3
   OR `id` = 5
   OR `id` = 15
   OR `id` = 56
   OR `id` = 34
   OR `id` = 47

2

SELECT *
FORM `somewhere`
WHERE 
  `id` IN (3,5,15,56,34,47)
like image 734
Silver Light Avatar asked Nov 26 '10 15:11

Silver Light


People also ask

What is MySQL query optimization?

MySQL provides optimizer control through system variables that affect how query plans are evaluated, switchable optimizations, optimizer and index hints, and the optimizer cost model. The server maintains histogram statistics about column values in the column_statistics data dictionary table (see Section 8.9.


2 Answers

The second approach is better. MySQL can optimize this.

MySQL has a problem with queries that use IN() statement - sometimes indexes can't be used. Is that really so, if I don't use a subquery?

There can be a problem with IN when you write IN(SELECT ...), but I don't think there is a problem with a simple list of values.

like image 195
Mark Byers Avatar answered Sep 25 '22 18:09

Mark Byers


If you really want to use indexes you can use UNION read more here mysql-followup-on-union-for-query-optimization-query-profiling

like image 36
cristian Avatar answered Sep 22 '22 18:09

cristian