0

I am not sure about the where clause in my SQL query. It is composed from more AND conditions and one Or condition. Now I have this

SELECT * FROM aaa 
WHERE server_id = 'xxx'
   OR (server_id != 'yyy' AND server_id != 'zzz' AND country != 'aaa' AND country != 'bbb')

I am not sure about that parenthesis. Is it neccesary or not?

Andrés
  • 487
  • 1
  • 12
Čamo
  • 3,863
  • 13
  • 62
  • 114
  • 2
    As it is the WHERE clause the parentheses are not needed because the AND operator has higher precedence than OR. – forpas Mar 21 '22 at 16:09
  • @jarlh it seems you are right. The 'xxx' condition is not needed at all. – Čamo Mar 21 '22 at 16:17
  • Thanks. You can write an answer. – Čamo Mar 21 '22 at 16:18
  • why is the `server_id = 'xxx'` condition not needed? It will match a row with `server_id = 'xxx' and country = 'aaa'` for example, which the version without it won't. – Esther Mar 21 '22 at 16:31
  • We can't tell whether the brackets are needed because we don't have anything to compare against (e.g. plain English specs of what the query needs to fetch). `and` has higher precedence than `or`, just like `×` has higher precedence than `+`. You need the brackets if you want to group operations differently. – Álvaro González Mar 21 '22 at 16:32
  • 1
    @ÁlvaroGonzález yes we can tell that the parentheses are not needed because the boolean expression: `server_id = 'xxx' OR (server_id != 'yyy' AND server_id != 'zzz' AND country != 'aaa' AND country != 'bbb')` is equivalent to `server_id = 'xxx' OR server_id != 'yyy' AND server_id != 'zzz' AND country != 'aaa' AND country != 'bbb'` because the operator AND has higher precedence than OR. What we can't tell is If these conditions meet the OP's requirement which we don't know. – forpas Mar 21 '22 at 17:36
  • @Čamo worth [reading](https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html). Take a look [here](https://stackoverflow.com/questions/4872180/how-exactly-does-using-or-in-a-mysql-statement-differ-with-without-parentheses), too. – Ergest Basha Mar 21 '22 at 18:37
  • @Čamo it will be better if you add some data examples and expected results. – Ergest Basha Mar 21 '22 at 18:38
  • @forpas thanks again. Now it is absolutely clear. – Čamo Mar 22 '22 at 08:34
  • @forpas Sorry for my poor wording. I was trying to say that we can't know if current bracket choice is correct (rather than redundant), but now I realise that I probably misunderstood the question altogether. I assumed the OP isn't sure about the overall correctness of his expression ("I am not sure about the where clause"). – Álvaro González Mar 23 '22 at 08:17
  • 1
    Personally I think relying on operator precedence for function behavior is a poor choice. Particularly the precedence in only one language, what if they changed rdbms? I think it's much clearer to read if conjunctions/disjunctions are grouped together (e.g. `(a AND b) OR (c AND (d OR e OR f))`) – Rogue Mar 23 '22 at 14:35

0 Answers0