It is a matter of operator precedence and associativity. When you use an expression composed of AND
and OR
, that is, relational operators, who are the ones who evaluate "binary values" and generate new ones according to Boolean algebra (see truth table and map of Karnaugh).
The AND
it’s like a multiplication and the OR
it’s like an addition, so no parentheses that change this precedence, which is next to the AND
is used primarily to the detriment of what is close to the OR
.
So read the codes like this to better understand:
(grupo = 'bebidas' AND preco < 10) OR estoque <= 100
grupo = 'bebidas' AND (preco < 10 OR estoque <= 100)
Like the AND
has natural precedence defined by the language the parentheses are not required in the first, but mandatory in the second to give the intended semantics in it.
In fact there are those who say, and I agree, that for these operators should always use the parentheses to make clear and explicit what the intention is and avoid mistakes unintentionally. Some say it should do for all operators, but this would be exaggerated, some no less intuitive than others for a "normal human".
To try to make a reading of what each expression is, that our friend tried but became very confused, so they must have negativated:
All that is of the GROUP of "drinks" And at the same time has below PRICE 10. But if this condition is not met, you can take a product that has a stock equal to or less than 100, so if something has stock below this limit counts as a bag to be considered in the selection, it doesn’t matter which group it belongs to or what the price is. Which seems pretty incoherent to me and seems like a mistake.
Anything from the "drinks" group at least one of the following two conditions: have PRICE less than 10 OR have stock equal to or less than 100. In this case being in the group "drink" happens to be mandatory for everyone. What also seems wrong, but who am I to talk without knowing what the problem is. It looks like everything should be valid and then there should be 2 AND
, which would dispense parentheses, although it can put to make more readable, although in this case change little.
Another question of readability is that it became barely visible where each clause is, it would be better to put the WHERE
in a single line or indent:
SELECT *
FROM PRODUTO
WHERE grupo = 'bebidas' AND
(preco < 10 OR estoque <= 100)
ORDER BY estoque DESC;
I put in the Github for future reference.
https://stackoverflow.com/a/1241158
– hkotsubo
i would make the second to be "defensive" tomorrow someone needs to change , say put the condition "AND item_active= ’S' the 1st would be wrong (no editing) the 2nd no.
– Motta