w3resource

MySQL NOT operator

NOT operator

MySQL NOT operator reverses or negates the input.

This function is useful in -

  • If you want to retrieve all records except those that meet a specific condition, NOT is invaluable.
  • It allows you to negate the result of a condition.
  • NOT makes queries more explicit. It clearly states that you want the opposite of a certain condition, which can help prevent misunderstandings or misinterpretations of your query.
  • When you have complex conditions involving multiple logical operators like AND and OR, NOT can be crucial for achieving the desired outcome.
  • NOT can be used to invert the logical meaning of a condition.
  • In some scenarios, NOT can be used to conditionally insert or update records based on the absence of a specific condition.
  • By using NOT judiciously, you can optimize your queries to efficiently retrieve the desired data.

Syntax:

NOT, !

The operator returns 1 if the operand is 0 and returns 0 if the operand is nonzero. It returns NULL if the operand is NOT NULL.

MySQL Version: 8.0

Example: MySQL NOT operator

In the following MySQL statement, NOT operator negates the input 10, it returns 0.

Code:

SELECT ! 10;

Output:

Example of MySQL NOT operator with zero input

In the following MySQL statement, NOT operator negates the input 0, it returns 1.

Code:

SELECT ! 0;

Output:

MySQL> SELECT ! 10;
+------+
| ! 10 |
+------+
|    0 | 
+------+
1 row in set (0.00 sec)

Example of MySQL NOT operator with zero input

In the following MySQL statement, NOT operator negates the input 0, it returns 1.

Output:

MySQL> SELECT ! 0;
+-----+
| ! 0 |
+-----+
|   1 | 
+-----+
1 row in set (0.00 sec)

Example of MySQL NOT operator with NULL

In the following MySQL statement, NOT operator negates the input NULL, it returns NULL.

Code:

SELECT ! NULL;

Output:

 MySQL> SELECT ! NULL;
+--------+
| ! NULL |
+--------+
|   NULL | 
+--------+
1 row in set (0.00 sec)
 

Example of MySQL NOT operator with non-zero input

In the following MySQL statement, NOT operator negates the input (10+10), it returns 0.

Code:

SELECT ! (10+10);

Output:

 MySQL> SELECT ! (10+10);
+-----------+
| ! (10+10) |
+-----------+
|         0 | 
+-----------+
1 row in set (0.00 sec)
 

Previous: AND operator
Next: OR operator



Follow us on Facebook and Twitter for latest update.