views:

23

answers:

2

The first one below works, but, just wanted to see if there's a better way...

If I'm trying to find all records that start with 'C' with either a flag of 2 or a status of 9, do I need to incorporate the 'C' criteria twice?

i.e.,

"SELECT * FROM mytable WHERE name like 'C%' AND flag = 2 OR name like 'C%' AND status = 9"

Or, is there a way quicker way to write it so that I only need to set 'C%' once?

+1  A: 

Logically, AND and OR are distributive to each other, i.e.

a & (b | c) = (a & b) | (a & c)

that means your condition can be rewritten as

name LIKE 'C%' AND (flag = 2 OR status = 9)
KennyTM
Oh, awesome... Thank you.
Dashiell0415
+1  A: 

OR has lower priority than AND so you need parentheses.

WHERE name LIKE "C%" AND (flag = 2 OR flag = 9)

you can also check for membership of a set of values

... AND flag IN (1, 9)

Peter Tillemans