Radagast
Radagast

Reputation: 1096

Best practice when filtering SQL results using OR in the WHERE part of the statement

I have been using mySQL Quite a bit however, this is the first time I am having to preform a query like the following. it works but I wonder if there is a better way to write it.

SELECT * FROM foo WHERE bar = 10058 or bar = 90234  or bar = 98211 or bar 4002 or bar = 90023

Is there a limit to the number of rows I can pull using this methodology? am I making a mistake? is there a better way?

FYI in this particular case bar will always be unique

Upvotes: 0

Views: 73

Answers (4)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

You want to use IN:

SELECT *
FROM `foo`
WHERE `bar` IN (10048, 90234, 98211, 4002, 90023)

Upvotes: 1

Rahul
Rahul

Reputation: 77876

You want a IN clause like

SELECT * FROM foo WHERE bar in (10058,90234,98211,4002,90023)

Anyways, internally your DB engine will expand it as a OR'ed stack at run time; i.e like

WHERE bar = 10058 or bar = 90234  or bar = 98211 or bar 4002 or bar = 90023

Upvotes: 0

Porco
Porco

Reputation: 4203

Use IN, like this:

SELECT * FROM foo WHERE bar IN (10058,90234,98211,4002,90023)

Upvotes: 5

Kris Gruttemeyer
Kris Gruttemeyer

Reputation: 872

You could condense the WHERE clause to:

SELECT * FROM foo WHERE bar in (10058,90234,98211,4002,90023)

Upvotes: 2

Related Questions