1

Need help with querying a list of names which start with either prefix1 or prefix2. These names should contain values ABC or DEF in their description(next column). Something like the below select query:

SELECT Name 
FROM Table 
WHERE Name LIKE 'X_%' 
   OR Name LIKE 'Y_%' 
  AND NextCol LIKE 'ABC%' 
   OR NextCol LIKE 'DEF%'

The result set should look like below:

 |-------|----------------|
 |Name   | NextCol        |
 |------ |----------------|
 |X_BLAH | ABCandsomething|
 |Y_BLAH | DEFandsomething|
 |X_BLAH | DEFandsomething|
 |Y_BLAH | ABCandsomething|

Can this be done using multiple 'like', 'and' and 'or' operators with wildcards or is there another better way to do it?

SqlZim
  • 37,248
  • 6
  • 41
  • 59
Joy
  • 13
  • 2

2 Answers2

3

You were only missing parenthesis, you were on the right track.

SELECT Name 
FROM Table 
WHERE (Name LIKE 'X_%' OR Name LIKE 'Y_%') AND (NextCol LIKE 'ABC%' OR NextCol LIKE 'DEF%')
Danieboy
  • 4,393
  • 6
  • 32
  • 57
1

Is this what you are looking for?

select Name
from Table
where (Name like 'X_%' or Name like 'Y_%') 
  and (NextCol like 'ABC%' or NextCol like 'DEF%')

Reference:

Community
  • 1
  • 1
SqlZim
  • 37,248
  • 6
  • 41
  • 59