Table 11.4. Logical Operators
| Name | Description |
|---|---|
AND, && | Logical AND |
NOT, ! | Negates value |
||, OR | Logical OR |
XOR | Logical XOR |
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;-> 1 mysql>SELECT -10 IS TRUE;-> 1 mysql>SELECT 'string' IS NOT NULL;-> 1
Logical NOT. Evaluates to
1if the operand is0, to0if the operand is nonzero, andNOT NULLreturnsNULL.mysql>
SELECT NOT 10;-> 0 mysql>SELECT NOT 0;-> 1 mysql>SELECT NOT NULL;-> NULL mysql>SELECT ! (1+1);-> 0 mysql>SELECT ! 1+1;-> 1The last example produces
1because the expression evaluates the same way as(!1)+1.Logical AND. Evaluates to
1if all operands are nonzero and notNULL, to0if one or more operands are0, otherwiseNULLis returned.mysql>
SELECT 1 && 1;-> 1 mysql>SELECT 1 && 0;-> 0 mysql>SELECT 1 && NULL;-> NULL mysql>SELECT 0 && NULL;-> 0 mysql>SELECT NULL && 0;-> 0Logical OR. When both operands are non-
NULL, the result is1if any operand is nonzero, and0otherwise. With aNULLoperand, the result is1if the other operand is nonzero, andNULLotherwise. If both operands areNULL, the result isNULL.mysql>
SELECT 1 || 1;-> 1 mysql>SELECT 1 || 0;-> 1 mysql>SELECT 0 || 0;-> 0 mysql>SELECT 0 || NULL;-> NULL mysql>SELECT 1 || NULL;-> 1Logical XOR. Returns
NULLif either operand isNULL. For non-NULLoperands, evaluates to1if an odd number of operands is nonzero, otherwise0is returned.mysql>
SELECT 1 XOR 1;-> 0 mysql>SELECT 1 XOR 0;-> 1 mysql>SELECT 1 XOR NULL;-> NULL mysql>SELECT 1 XOR 1 XOR 1;-> 1a XOR bis mathematically equal to(a AND (NOT b)) OR ((NOT a) and b).