0

I have the following mysql query:

SELECT * FROM `notifications` 
WHERE `receiverUserID` = 3 AND `status` = 0 AND `typ` = 1 OR `typ` = 2

the result:

enter image description here

But my query is not correct. The result should show me only data where typ = 1 OR 2, status = 0 and the receiverUserID = 3

the row where receiverUserID = 2 should not be shown. Where is my mistake ?

3
  • WHERE `receiverUserID` = 3 AND `status` = 0 AND (`typ` = 1 OR `typ` = 2) Commented May 30, 2020 at 8:11
  • See meta.stackoverflow.com/questions/333952/… Commented May 30, 2020 at 8:14
  • Note that the row with receiverUserID = 3 should also not be shown since it has status = 1 Commented May 30, 2020 at 8:15

2 Answers 2

3

You need to shorten down the scope of OR operator by using parenthesis. So your query should be

SELECT * FROM notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2 );

Edit 1 (Helpful comment by @jBuchholz)

Here is a list of operator precedences in MySQL dev.mysql.com/doc/refman/8.0/en/operator-precedence.html AND has higher precedence than OR and is therefore executed earlier (like multiplication is executed before addition).

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

2 Comments

In addition: here is a list of operator precedences in mysql dev.mysql.com/doc/refman/8.0/en/operator-precedence.html AND has a higher precedence than OR and is therefore executed earlier (like multiplication is executed before addition).
@jBuchholz Thanks a lot for adding a much valuable thing. Appreciate it. If you allow, may I add it in my answer?
1

Here is what your query was actually doing:

SELECT * FROM
notifications
WHERE (receiverUserID = 3 AND status = 0 AND typ = 1) OR typ = 2;

This is due to that AND takes greater precedence than OR. This explains why all those typ = 2 records appear in your result set. You need to use parentheses to enforce the and/or logic you have in mind:

SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2);

Note that had used WHERE IN (...) syntax this would have been a moot point:

SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND typ IN (1, 2);

Comments

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.