Search code examples
sql-serverwildcardsql-likeor-operatorand-operator

SQL Server LIKE, WILDCARDS, AND, OR operator, braces


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?


Solution

  • 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%')