Skip to content

Comparison operators

View as Markdown

Comparison operators compare two values and return 1 (true), 0 (false) or NULL (unknown).

expression comparison_operator expression
expression IS [NOT] {TRUE | FALSE | UNKNOWN | NULL}
comparison_operator ::= = | <=> | <> | != | > | < | >= | <=
Operator Meaning Example Result
= Equal. NULL if either operand is NULL. 1 = 2, 1 = NULL 0, NULL
<=> NULL-safe equal: like =, but two NULL values are equal and a NULL compared with a value is false, never NULL. 1 <=> NULL, NULL <=> NULL 0, 1
<>, != Not equal. 1 <> 2 1
>, <, >=, <= Greater than, less than, greater or equal, less or equal. 1 >= 2 0
IS [NOT] TRUE, IS [NOT] FALSE Tests the truth value of the left operand. 1 IS FALSE, 1 IS NOT FALSE 0, 1
IS [NOT] UNKNOWN, IS [NOT] NULL Tests whether the left operand is NULL. NULL IS UNKNOWN 1

How values of each type are compared:

  • Numbers: values of different numeric types are converted to a common type first, so 1.000 = 1 is true.
  • Character strings: compared according to their collation. With the default utf8_bin collation, the comparison is case-sensitive. When two strings of different lengths are compared, the shorter one is padded with spaces for CHAR values.
  • Strings and numbers: the string is converted to a number, so 0.01 = '0.01' is true. Prefer comparing values of the same type, which also lets the optimizer use indexes.
  • Dates and times: an earlier time is smaller. Values of different date/time types are converted to a common type; compare values of the same type to get the result you expect.
  • Bit strings: the shorter value is padded with zeros at the end.
  • Collections: LIST values are compared element by element in order; for SET and MULTISET values, use the containment operators.
  • NULL: any comparison with NULL using =, <>, < and so on returns NULL. Use IS NULL or <=> instead.
SELECT (1 <> 0), (1 = NULL), (1 <=> NULL), (NULL <=> NULL), (1.000 = 1),
('coradb' = 'CoraDB'), (0.01 = '0.01'), (1 IS NOT FALSE)
FROM db_root;
(1 <> 0) (1 = NULL) (1 <=> NULL) (NULL <=> NULL) (1.000 = 1) ('coradb' = 'CoraDB') (0.01 = '0.01') (1 IS NOT FALSE)
1 NULL 0 1 1 0 1 1

<=> makes it easy to compare with a value that may be NULL. The nine unshipped orders:

SELECT COUNT(*) FROM orders WHERE shipped_date <=> NULL;
count(*)
9