Link to home
Start Free TrialLog in
Avatar of theideabulb
theideabulbFlag for United States of America

asked on

Help with search filtering query

I am looking for the best ways to do a search, but to also have keywords to exclude to really filter down results

Here is an example, I am looking for 'prince of persia', but I want to make sure that all the titles do not have any form of minifigure in it.

select * from products
where item_title like '%prince of persia%'
and item_title not like '%minifigure%'
or item_title not like '%minifig%'
or item_title not like '%mini-figure%'


Is there a better way to do this?  This started bringing back results that didn't have 'prince of persia' at all!!
ASKER CERTIFIED SOLUTION
Avatar of jimyX
jimyX

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jimyX
jimyX

If you might have 'mini-fig' then use
select * from products where item_title like '%prince of persia%' and (item_title not like '%mini%figure%' or item_title not like '%mini%fig%')
Avatar of theideabulb

ASKER

Wow, the parenthese made a huge difference.  Why does that make such a difference?
Because the OR condition is evaluated same level as the AND condition and here you get the overall result by evaluating the first and the second conditions, then their result is evaluated against the third condition and so on. If there is one OR condition as True then it suppresses the AND.

To make sure the result is from the main condition which is to be having 'prince of persia' in the field, we separate the AND to be alone and the rest of OR's evaluated together and then compared with the AND at the end.

So without parentheses it turns out to be:
select * from products
where item_title like '%prince of persia%'     (False)
and item_title not like '%minifigure%'            (True)
or item_title not like '%minifig%'                    (True)
or item_title not like '%mini-figure%'              (False)

False and True or True or False   ->   False or True or False   ->   True or False   ->   overall = True

With parentheses:
select * from products
where item_title like '%prince of persia%'     (False)
and (item_title not like '%minifigure%'            (True)
or item_title not like '%minifig%'                    (True)
or item_title not like '%mini-figure%')              (False)

False and (True or True or False)   ->   False and (True)   ->   overall = False
Thanks for the sql tip.  That will really help me out.  Good example, you should right a book :)