Search code examples
mysqlsqlnot-operator

Can the NOT operator work on multiple conditions present in parenthesis?


I run following query in MySQL :

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

It returned me exactly the correct expected result.

After that I run following query :

SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and

Solution

  • You got bitten by operator priority. Parentheses are your friend, you see.

    WHERE NOT Country='Germany' AND NOT Country='USA';
    

    actually means, since NOT has precedence over AND:

    WHERE (NOT Country='Germany') AND (NOT Country='USA');
    

    Since "NOT a=b" is "a!=b", this means:

    WHERE Country!='Germany' AND Country!='USA';
    

    which, as the others pointed out, looks muuuuch better like this:

    WHERE Country NOT IN ('Germany', 'USA');
    

    Now, next topic. This one:

    WHERE NOT (Country='Germany' AND Country='USA');
    

    Country can not be Germany and USA at the same time, so the stuff inside the () is always FALSE, so this equates to:

    WHERE NOT (FALSE);
    

    i.e.

    WHERE TRUE;
    

    ie, you get your whole table.