The MySQL GREATEST()
function is a comparison function that returns the largest value from a list of values.
The list of values is provided as multiple arguments. So in other words, GREATEST()
returns the maximum-valued argument from a list of arguments.
Syntax
The syntax of GREATEST()
goes like this:
GREATEST(value1,value2,...)
Each argument is separated by a comma. This function compares them all and returns the one with the largest value.
Example 1 – Comparing Numbers
If all arguments are integers, they’re compared as integers.
SELECT GREATEST(12, 120, 2400) AS 'Result';
Result:
+--------+ | Result | +--------+ | 2400 | +--------+
If at least one argument is double precision, they are compared as double-precision values. Otherwise, if at least one argument is a DECIMAL
value, they are compared as DECIMAL
values.
SELECT GREATEST(12.00, 120, 2400) AS 'Result';
Result:
+---------+ | Result | +---------+ | 2400.00 | +---------+
See below for the exact rules for determining the return value.
Example 2 – Comparing Strings
Here’s an example of comparing strings.
SELECT GREATEST('a', 'b', 'c') AS 'Result';
Result:
+--------+ | Result | +--------+ | c | +--------+
Here’s another one:
SELECT GREATEST('Cat', 'Dogg', 'Rat') AS 'Result';
Result:
+--------+ | Result | +--------+ | Rat | +--------+
Example 3 – NULL Values
If any of the arguments is NULL
, the result is NULL
.
SELECT GREATEST('a', NULL, 'c') AS 'Result';
Result:
+--------+ | Result | +--------+ | NULL | +--------+
Comparison Rules
Certain rules are applied when determining what the return value will be. These rules are as follows:
- If any argument is
NULL
, the result isNULL
. No comparison is needed. - If all arguments are integer-valued, they are compared as integers.
- If at least one argument is double precision, they are compared as double-precision values. Otherwise, if at least one argument is a
DECIMAL
value, they are compared asDECIMAL
values. - If the arguments comprise a mix of numbers and strings, they are compared as numbers.
- If any argument is a nonbinary (character) string, the arguments are compared as nonbinary strings.
- In all other cases, the arguments are compared as binary strings.