Skip to content

Comparison functions ​

Comparison functions select extrema from a list of expressions. They return one of the original values, preserving its type.

greatest and least skip NULL arguments. The scalar forms of min and max return NULL if any argument is NULL; their one-argument aggregate forms instead skip NULL rows. Choose the function according to the missing-value behavior you need.

Example: Comparing optional values ​

sql
SELECT greatest(10, NULL, 20), least(10, NULL, 20), max(10, NULL, 20)
FORMAT csv;
text
20,10,\N

greatest ​

Return the largest non-NULL argument using SQL value ordering and the selected collation.

Syntax ​

text
greatest(value1, ...)

Arguments ​

One or more SQL values; NULL arguments are skipped. Comparisons follow local SQL value ordering rather than PostgreSQL implicit common-type coercion.

Returned value ​

Selected argument with its type preserved; NULL if every argument is NULL.

Example ​

sql
SELECT greatest(1,NULL,3) FORMAT csv;
text
3

least ​

Return the smallest non-NULL argument using SQL value ordering and the selected collation.

Syntax ​

text
least(value1, ...)

Arguments ​

One or more SQL values; NULL arguments are skipped. Comparisons follow local SQL value ordering rather than PostgreSQL implicit common-type coercion.

Returned value ​

Selected argument with its type preserved; NULL if every argument is NULL.

Example ​

sql
SELECT least(1,NULL,-2) FORMAT csv;
text
-2

max ​

Return the largest of two or more values using SQL value ordering and collation.

Syntax ​

text
max(value1, value2, ...)

Arguments ​

Two or more SQL values. Any NULL argument makes the result NULL; one argument selects the aggregate form.

Returned value ​

The selected input value with its type preserved, or NULL when any argument is NULL.

Example ​

sql
SELECT max(3,1,2) FORMAT csv;
text
3

min ​

Return the smallest of two or more values using SQL value ordering and collation.

Syntax ​

text
min(value1, value2, ...)

Arguments ​

Two or more SQL values. Any NULL argument makes the result NULL; one argument selects the aggregate form.

Returned value ​

The selected input value with its type preserved, or NULL when any argument is NULL.

Example ​

sql
SELECT min(3,1,2) FORMAT csv;
text
1