Home » Php » mysql – How can I combine ANDs and ORs in my SQL statement

mysql – How can I combine ANDs and ORs in my SQL statement

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have this SQL statement:

SELECT * FROM `table` WHERE type = 3 OR type = 5 OR type = 4 and table.deleted = 1;

I’ve read that I can use parenthesis to accomplish this but I was wondering if then this would be valid:

SELECT * FROM `table` WHERE (type = 3 OR type = 5 OR type = 4) and table.deleted = 1;

OR

SELECT * FROM `table` WHERE (type = 3 OR type = 5) OR type = 4 and table.deleted = 1;
How to&Answers:

Both of these would be valid, but since AND has higher precedence than OR, they would mean different things:

  • Your first parenthesized query would pick deleted rows with types 3, 4, 5
  • Your second parenthesized query would select all rows with types 3, 5, in addition to deleted rows of type 4; this is the same meaning as in the original query without parentheses.

You can avoid the confusion altogether by using operator IN, like this:

SELECT * FROM `table` WHERE type IN (3, 4, 5) AND table.deleted = 1;

or if you wanted the second meaning

SELECT * FROM `table` WHERE type IN (3, 5) OR (type = 4 AND table.deleted = 1)

Answer:

What you need is IN operator like

SELECT * FROM `table` 
WHERE type IN ( 3, 5, 4) and deleted = 1;

Answer:

AND has higher precedence than OR, so your first and third filters are equivalent to:

type = 3 OR type = 5 OR (type = 4 and table.deleted = 1)

Your second filter could equivalently be expressed using IN():

type IN (3, 5, 4) and table.deleted = 1