How do I not repeat myself in this SQL query?

67 Views Asked by At

I've started learning SQL and I'm trying to reduce my repetition. Can someone help with this?

SELECT email
FROM users 
WHERE campaign LIKE 'BBB-2'
AND test ='lions' 
OR test = 'tigers' 
OR test = 'bears'; 
3

There are 3 best solutions below

1
On

Use in:

SELECT email
FROM users 
WHERE campaign = 'BBB-2' AND test IN ('lions' , 'tigers' , 'bears'); 

Notes:

  • this solves a logical prescendence issue in your original query: the ORed condition needed to be surrounded by parentheses

  • I replaced the LIKE condition with an equality check; there is no point using LIKE when the right operand contains no wildcard

0
On

Use IN:

WHERE campaign LIKE 'BBB-2' AND
      test IN ('lions' , 'tigers' , 'bears'); 

As a bonus this will fix a logic bug in your query. Presumably, you want the campaign condition to filter all rows, not just those with 'lions'.

0
On

You could use the below:

    SELECT email
    FROM users 
    WHERE campaign LIKE 'BBB-2'
    AND test IN('lions','tigers','bears')