Skip to main content

Add parentheses in nested expression

An AND condition has a higher precedence than an OR condition, so you should wrap the AND condition in parentheses for clarity and to ensure that the operators are evaluated in the order that you intend.

Consider this example:

SELECT dogs.name
FROM dogs
WHERE dogs.sex = 'male'
and dogs.color = 'white'
or dogs.size = 'big';

Without parentheses, one would think that it is equivalent to:

SELECT dogs.name
FROM dogs
WHERE dogs.sex = 'male'
and (dogs.color = 'white' or dogs.size = 'big');

But the original query is parsed as:

SELECT dogs.name
FROM dogs
WHERE (dogs.sex = 'male' and dogs.color = 'white')
or dogs.size = 'big';