caner taşdemir caner taşdemir - 2 months ago 6
MySQL Question

mySQL - Is there a better way of using many OR oparators in query?

I have a huge members database. Let's say I have 10 names.
I need to fetch these members' last seen values from members table in a fastest way. I have tried

SELECT lastseen FROM members WHERE
name='Pierce' OR
name='John' OR
name='Steven' OR
name='James' OR
name='Ernie' OR
name='Stuart' OR
name='Blake' OR
name='Shaun' OR
name='Pat' OR
name='Lola'


But using many OR oparators in the query is an unprofessional way and slow, are there better methods ?

Answer

Use IN:

SELECT lastseen
FROM members
WHERE name IN ('Pierce', 'John', . . . )

In MySQL, there is even a performance advantage to using IN instead of ORs. MySQL will create a binary tree for searching the values (assuming they are constants), which speeds up the processing.