# 12.3.3. Logical Operators

Table 12.4. Logical Operators

In SQL, all logical operators evaluate to `TRUE`, `FALSE`, or `NULL` (`UNKNOWN`). In MySQL, these are implemented as 1 (`TRUE`), 0 (`FALSE`), and `NULL`. Most of this is common to different SQL database servers, although some servers may return any nonzero value for `TRUE`.

MySQL evaluates any nonzero, non-`NULL` value to `TRUE`. For example, the following statements all assess to `TRUE`:

```mysql> `SELECT 10 IS TRUE;`-> 1mysql> `SELECT -10 IS TRUE;`-> 1mysql> ```SELECT
'string' IS NOT NULL;```-> 1```
• Logical NOT. Evaluates to `1` if the operand is `0`, to `0` if the operand is nonzero, and `NOT NULL` returns `NULL`.

`mysql> `SELECT NOT 10;`        -> 0mysql> `SELECT NOT 0;`        -> 1mysql> `SELECT NOT NULL;`        -> NULLmysql> `SELECT ! (1+1);`        -> 0mysql> `SELECT ! 1+1;`        -> 1`

The last example produces `1` because the expression evaluates the same way as `(!1)+1`.

• Logical AND. Evaluates to `1` if all operands are nonzero and not `NULL`, to `0` if one or more operands are `0`, otherwise `NULL` is returned.

```mysql> ```SELECT 1 &&
1;```        -> 1mysql> ```SELECT 1 &&
0;```        -> 0mysql> ```SELECT 1 &&
NULL;```        -> NULLmysql> ```SELECT 0 &&
NULL;```        -> 0mysql> ```SELECT NULL &&
0;```        -> 0```
• Logical OR. When both operands are non-`NULL`, the result is `1` if any operand is nonzero, and `0` otherwise. With a `NULL` operand, the result is `1` if the other operand is nonzero, and `NULL` otherwise. If both operands are `NULL`, the result is `NULL`.

`mysql> `SELECT 1 || 1;`        -> 1mysql> `SELECT 1 || 0;`        -> 1mysql> `SELECT 0 || 0;`        -> 0mysql> `SELECT 0 || NULL;`        -> NULLmysql> `SELECT 1 || NULL;`        -> 1`
• Logical XOR. Returns `NULL` if either operand is `NULL`. For non-`NULL` operands, evaluates to `1` if an odd number of operands is nonzero, otherwise `0` is returned.

`mysql> `SELECT 1 XOR 1;`        -> 0mysql> `SELECT 1 XOR 0;`        -> 1mysql> `SELECT 1 XOR NULL;`        -> NULLmysql> `SELECT 1 XOR 1 XOR 1;`        -> 1`

`a XOR b` is mathematically equal to ```(a AND (NOT b)) OR ((NOT a) and b)```.

Spec-Zone.ru - all specs in one place