Arithmetic and logical operators
+, -, *, /, DIV, %, MOD, unary minus and AND, OR, XOR, NOT: exactness, division, results and three-valued logic.
Arithmetic#
a + b a - b a * b a / b a DIV b a % b a MOD b -a +a| Operator | Result |
|---|---|
+, -, * | the sum, difference, product |
/ | the exact quotient, a decimal; NULL if b is 0 |
DIV | the quotient cut to a whole number; NULL if b is 0 |
%, MOD | the remainder; NULL if b is 0 |
unary - | negation; + changes nothing |
Remarks:
- Exact. On whole numbers and decimals the operators are exact up to 128 bits (so
BIGINT UNSIGNEDarithmetic keeps all digits; the result of a whole-number operation that does not fit 64 bits is a decimal with its digits). AFLOAT,DOUBLEor text operand makes the result aDOUBLE. - Division. The result of
/has the scale of the dividend plusdiv_precision_increment(default 4), rounded half away from zero:7 / 2is3.5000. A division of whole numbers is a decimal, not a whole number.SET div_precision_increment = nchanges the extra digits. - Division by zero gives
NULL, in everysql_mode(the modeERROR_FOR_DIVISION_BY_ZEROis stored but changes nothing). - Types. The type of the result (the column type in
CREATE TABLE ... AS SELECT) is that MySQL gives:INTwhile the width is at most 11, thenBIGINT;DECIMAL(p+4, s+4)for/; unsigned when both sides are unsigned or literal. - Text. A text operand is read as a number (
'10' + 5is 15). - Dates.
date + INTERVAL n unitanddate - INTERVAL n unit(see Date and time functions). - MySQL's error 1690 (unsigned result out of range) is not raised.
SELECT 7 / 2, 7 DIV 2, 7 % 2, -7 % 3, 1 / 0, 2 * 3.5, '10' + 5, 18446744073709551615 + 0;
SELECT w, n * 2 AS dbl, n / 2 AS half, n % 2 AS m FROM words ORDER BY w;Logical#
a AND b a && b a OR b a || b a XOR b NOT a !a| Operator | Result |
|---|---|
AND, && | 1 if both are true; 0 if one is false; else NULL |
OR, || | 1 if one is true; 0 if both are false; else NULL |
XOR | 1 if exactly one is true, 0 if both or neither; NULL if either is NULL |
NOT, ! | 1 if the value is false, 0 if true, NULL for NULL |
Remarks:
- A value is true if it is not 0, false if it is 0. Text counts as the number it reads as (
'abc'is false,'1abc'is true). ||isOR, as in MySQL's default mode. It does not concatenate: useCONCAT.- The evaluation is three-valued; see NULL handling.
XORis read at the same level asOR;!at the level ofNOT. See Expressions and operator precedence.TRUEandFALSEare 1 and 0.
SELECT 1 AND 0, 1 OR 0, 1 XOR 1, NOT 1, NULL AND 0, NULL OR 1;
SELECT COUNT(*) FROM words WHERE n > 1 AND (w LIKE 'a%' OR w LIKE 'b%');