SQL Least and Greatest

November 5, 2012

The least and greatest functions work in a similar way to coalesce, in that you can pass in any number of parameters, and the function will return the highest of them all. Parameters can be static values or columns.

SELECT LEAST(44,777,33,22,11)

returns the following on postgres.

least 
-------
    11
(1 row)

To do the same on Oracle, you'll need to select from dual.

Likewise, greatest returns the largest value:

SELECT GREATEST(44,777,33,22,11);

returns

 greatest 
----------
      777
(1 row)

Strings

This also works with strings:

SELECT GREATEST('abc','drum','coder','zzz');

gives

 greatest 
----------
 zzz
(1 row)

whilst

SELECT LEAST('abcess','abc','drum','coder','zzz')

gives

 least 
-------
 abc
(1 row)