1

I'm trying to exclude rows that contain two words. In more details, I want to include rows that contain uber, but don't include rows that contain uber eats.

I'm using this condition:

WHERE LOWER(name) LIKE '%uber%'  
AND NOT (LOWER(name) LIKE '%ubereats%' AND LOWER(name) LIKE '%uber%eats%')

But I still get some unwanted rows like the following:

UBER   EATS
UBER   *EATS
UBER* EATS

In a query, I need to exclude any of uber eats related ones. In a separate query, I want only those that are related to uber eats.

1
  • 2
    Try OR instead of AND: NOT (LOWER(name) LIKE '%ubereats%' OR LOWER(name) LIKE '%uber%eats%') Commented Jul 25, 2022 at 3:59

1 Answer 1

3

Basically, you need OR instead of AND. Plus parentheses due to operator precedence (AND binds stronger than OR):

WHERE  LOWER(name) LIKE '%uber%'  
AND    NOT (LOWER(name) LIKE '%ubereats%' OR
            LOWER(name) LIKE '%uber%eats%')

Or keep the AND and switch to NOT LIKE:

WHERE  LOWER(name) LIKE '%uber%'  
AND    LOWER(name) NOT LIKE '%ubereats%'
AND    LOWER(name) NOT LIKE '%uber%eats%';

But since % in LIKE patterns stands for 0 or more characters, LOWER(name) LIKE '%ubereats%' is completely redundant. So:

WHERE  LOWER(name) LIKE '%uber%'  
AND    LOWER(name) NOT LIKE '%uber%eats%'

Or simplify altogether with regular expressions:

WHERE name ~* 'uber'  
AND   name !~* 'uber.*eats'

db<>fiddle here

See:

I am not sure your original expressions capture your objective precisely, though.

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it be 'uber.*eats' instead of 'uber.?eats'?
@ThorstenKettner: Yes, that's a closer fit to the original in the question. (Though it may be the OP really wants a more restrictive pattern, like illustrated in the fiddle with "uber has seats".)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.