Can one group LIKEs together?

Can one group LIKEs together, such as:
select * from A 
 where B like ('ccc', 'ddd', 'eee')

    Requires Free Membership to View

No. You have to "distribute" the LIKE operator over the individual items in your list. This is not just a syntax requirement, it is also good coding practice, because it allows you to concentrate on exactly what you mean.

First, you will need to decide whether you want the conditions connected with ORs or ANDs. Second, if you want all three strings present, do the strings have to exist in the given sequence? Finally, you should really use wildcard characters; otherwise, each LIKE in effect becomes a strict equality, and then only the OR version even makes sense.

Find rows where B contains any one (or two, or three) of the three strings:

select * 
  from A 
 where B like '%ccc%'
    or B like '%ddd%'
    or B like '%eee%'

Find rows where B contains all three strings, in any order:

select * 
  from A 
 where B like '%ccc%'
   and B like '%ddd%'
   and B like '%eee%'

Find rows where B contains all three strings, in the given order:

select * 
  from A 
 where B like '%ccc%ddd%eee%'

For More Information


This was first published in December 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.