13

I would like to perform a SELECT query with MySQL. My goal is to select all the dogs in a vet database that would be sex=male and fur=short and (color=black or size=big)

Note: I want to select dogs that are either black or size is big. They don't have to fulfill the 2 requirements. They just need to fulfill either one.

I have written the SQL statement below but I'm not not sure if I'm right:

SELECT name, sex, fur, color 
FROM dogs 
WHERE TRUE sex='male' AND fur='short' AND color='black' OR size="big";

Pardon my phrasing if it's too confusing.

Rehan Shah
  • 1,505
  • 12
  • 28
dave
  • 229
  • 1
  • 3
  • 13

5 Answers5

32

According to Operator precedence for MySQL AND has higher precedence than OR.

So C1 AND C2 OR C3 will be treated as (C1 AND C2) OR C3

To override the default precedence you need to use parenthesis as:C1 AND (C2 OR C3)

In your case the right query is:

SELECT name, sex, fur, color 
FROM dogs 
WHERE sex='male' AND fur='short' AND (color='black' OR size="big");
codaddict
  • 445,704
  • 82
  • 492
  • 529
4

Make sure to add parentheses, so the OR condition gets evaluated correctly.

SELECT name, sex, fur, color 
FROM dogs 
WHERE sex='male' AND fur='short' AND (color='black' OR size='big');
Lance Rushing
  • 7,540
  • 4
  • 29
  • 34
1

The way you use parentheses in the description of your goal is correct. The syntax is:

SELECT name, sex, fur, color 
    FROM dogs 
    WHERE sex="male" AND fur="short" AND (color="black" OR size="big");
cherouvim
  • 31,725
  • 15
  • 104
  • 153
0

I have used this and its working;

SELECT name, sex, fur, color 
FROM dogs 
WHERE sex="male" AND fur="short" AND (color="black" || size="big");
Matt
  • 74,352
  • 26
  • 153
  • 180
0

select name, sex, fur,color from dogs where sex ='male' and fur = 'short' and (color ='black' or size ='big');

Channa
  • 742
  • 17
  • 28