Search code examples
sqlwhere-clausesql-like

Sql like pulling different amount of results


Im trying to work out some groups which will take any word like what im looking for and eventually group them together, however when I use the like in the where statement one way I get more results than when I use it the other way and I just wondered why?

If I use this is the where statement I get more results as its pulling out anything like the word ive listed including ones that have whitespace before/after

and name like '%offer1%'
or name like '%offer2%' 
or name like '%offer3%' 
or name like '%offer4%' -- 244

However when I search each word separate I get less values as its not getting the words where there may e white space after and I just wondered why really? For the below code I just ran each of these individually rather than all together like shows as I had commented them out each time to get the counts which are at the end of the row

and name like '%offer1%' -- 97
and name like '%offer2%' -- 38
and name like '%offer3%' -- 2
and name like '%offer4%' -- 6 (143)

Solution

  • The problem is your WHERE statement, which is not shown here.

    where <condition>
    and name like '%offer1%'
    or name like '%offer2%' 
    or name like '%offer3%' 
    or name like '%offer4%' 
    

    This is interpreted as :

    where (<condition> and name like '%offer1%') 
    or (name like '%offer2%')
    or (name like '%offer3%')
    or (name like '%offer4%')
    

    Which is not the same as what you originally wanted to achieve.

    You should change your query using parenthesis :

    and (name like '%offer1%'
    or name like '%offer2%' 
    or name like '%offer3%' 
    or name like '%offer4%')