PostgreSQL Tutorial PostgreSQL Advanced PostgreSQL Database Account Management PostgreSQL References
PostgreSQL Tutorial PostgreSQL Advanced PostgreSQL Database Account Management PostgreSQL References

PostgreSQL GREATEST() Function



The PostgreSQL GREATEST() function returns the greatest value in a list of expressions. The expressions must all be convertible to a common data type, which will be the type of the result. NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL.

Syntax

GREATEST(expr1, expr2, ... expr_n)

Parameters

expr1, expr2, ... expr_n Required. Specify the list of expressions to be evaluated.

Return Value

Returns the greatest value in a list of expressions.

Example 1:

The example below shows the usage of GREATEST() function.

SELECT GREATEST(20, 30, 60, 10);
Result: 60

SELECT GREATEST('20', '30', '60', '10');
Result: '60'

SELECT GREATEST('D', 'G', 'X', 'A');
Result: 'X'

SELECT GREATEST('Alpha', 'Beta', 'Delta', 'Gamma');
Result: 'Gamma'

SELECT GREATEST('Alpha1', 'Alpha2', 'Alpha3', 'Alpha4');
Result: 'Alpha4'

SELECT GREATEST(20, 30, 60, 10, NULL);
Result: 60

Example 2:

Consider a database table called Sample with the following records:

Dataxyz
Data 110011
Data 2201512
Data 3303013
Data 4404514
Data 5506015

To get the greatest value, when values of column x, column y and column z are compared, the following query can be used:

SELECT *, GREATEST(x, y, z) AS GREATEST_Value FROM Sample;

This will produce the result as shown below:

DataxyzGREATEST_Value
Data 11001111
Data 220151220
Data 330301330
Data 440451445
Data 550601560

❮ PostgreSQL Functions