SQL reference (MySQL and MariaDB dialects)

Arithmetic and logical operators

+, -, *, /, DIV, %, MOD, unary minus and AND, OR, XOR, NOT: exactness, division, results and three-valued logic.

Arithmetic#

SQL
a + b      a - b      a * b      a / b      a DIV b      a % b      a MOD b      -a      +a
OperatorResult
+, -, *the sum, difference, product
/the exact quotient, a decimal; NULL if b is 0
DIVthe quotient cut to a whole number; NULL if b is 0
%, MODthe 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 UNSIGNED arithmetic keeps all digits; the result of a whole-number operation that does not fit 64 bits is a decimal with its digits). A FLOAT, DOUBLE or text operand makes the result a DOUBLE.
  • Division. The result of / has the scale of the dividend plus div_precision_increment (default 4), rounded half away from zero: 7 / 2 is 3.5000. A division of whole numbers is a decimal, not a whole number. SET div_precision_increment = n changes the extra digits.
  • Division by zero gives NULL, in every sql_mode (the mode ERROR_FOR_DIVISION_BY_ZERO is stored but changes nothing).
  • Types. The type of the result (the column type in CREATE TABLE ... AS SELECT) is that MySQL gives: INT while the width is at most 11, then BIGINT; DECIMAL(p+4, s+4) for /; unsigned when both sides are unsigned or literal.
  • Text. A text operand is read as a number ('10' + 5 is 15).
  • Dates. date + INTERVAL n unit and date - INTERVAL n unit (see Date and time functions).
  • MySQL's error 1690 (unsigned result out of range) is not raised.
SQL
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#

SQL
a AND b      a && b      a OR b      a || b      a XOR b      NOT a      !a
OperatorResult
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
XOR1 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).
  • || is OR, as in MySQL's default mode. It does not concatenate: use CONCAT.
  • The evaluation is three-valued; see NULL handling.
  • XOR is read at the same level as OR; ! at the level of NOT. See Expressions and operator precedence.
  • TRUE and FALSE are 1 and 0.
SQL
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%');

See also#