What is GREATEST() in SQL?

The GREATEST() function returns the greatest value from a list of arguments.

Figure 1 shows a visual representation of the GREATEST() function.

Figure 1: Visual representation of GREATEST() function

Syntax

GREATEST(arg1, arg2, .... argn)

Parameter

The GREATEST() function takes n number of arguments as a parameter.

Arguments can be of any data type, such as integer, float, string, etc.

Return value

The GREATEST() function returns the greatest value from the list of arguments sent as a parameter.

  • If any argument is NULL, then this function will return NULL.
  • If the arguments are a mixture of integers and strings, then this function will compare them as numbers.
  • If any argument is a non-binary string, then this function will compare all the arguments as non-binary strings.
  • If two or more arguments have the greatest value, then this function will return the first occurring greatest value.

Code

-- NULL as argument
SELECT GREATEST(NULL,10,3,4,6,9);
-- integers as argument
SELECT GREATEST(5,10,3,4,6,9);
-- floats as arguments
SELECT GREATEST(4.9,4.6,4.5,4.2,4.1);
-- strings as argument
SELECT GREATEST('educative', 'edpresso');
-- mixture of strings and integer
-- first '10' and '0' will be casted as integer and then comparison is done
SELECT GREATEST('10',1,'0');

Free Resources