2

I am using the following query to get data from mysql database and I get wrong data. I want to get all data with the cart_Status of 2 or 3 which have the view_Status of 1:

SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3

This is how my data structure and table looks like:

enter image description here

But in result, it returns something regardless of view_Status = 1 which is not my target.

it returns :

enter image description here

Of course, it should not return anything! But, it does!

1
  • 1
    Try this SELECT * FROM cart` WHERE view_Status = 1 AND (cart_Status = 2 OR cart_Status = 3)` Commented Feb 8, 2017 at 4:05

4 Answers 4

3

This is about operator precendence.
Your query evaluates as

SELECT * FROM `cart` WHERE (`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3

You should to add parentheses:

SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)
Sign up to request clarification or add additional context in comments.

2 Comments

Oops! I forgot that. Thanks :-)
Called operator precendence in any programming language.
2
SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)

or better

SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status in (2, 3);

Comments

1

You appear to be learning SQL. Use parentheses in the WHERE clause, particularly when you mix AND and OR.

However, in your case, IN is a better solution:

SELECT c.*
FROM `cart` c
WHERE c.view_Status = 1 AND cart_Status IN (2, 3);

Comments

1

It's a problem with operators precedence. Typically AND is executed before OR in programming languages (think of AND as of multiplication of bits, and of OR as of addition of bits and precedence becomes familiar). So, your condition:

`view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3

is parsed like this:

(`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3

which results in all rows with specific cart_Status to be selected. You have to add parenthesis around the second clause:

`view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)

or, even shorter:

`view_Status` = 1 AND cart_Status IN (2, 3)

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.