Summary: in this tutorial, you’ll learn how to use the PostgreSQL LEAST
function to select the lowest value from a list of values.
Getting Started with the PostgreSQL LEAST function #
The LEAST
function accepts a list of values and returns the smallest value.
Here’s the syntax of the LEAST
function:
LEAST (expression1, expression2, ....)
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
The LEAST
function ignores NULL
. It’ll return NULL
if all expressions evaluate to NULL
.
In SQL standard, the LEAST
function returns NULL
if any expression evaluates to NULL
. Some database systems behave this way such as MySQL.
Basic PostgreSQL LEAST function examples #
The following example uses the LEAST
function to return the lowest number in the list:
SELECT LEAST(1,2,3) lowest;
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
lowest
---------
1
The LEAST
function returns 3 because it is the lowest number in the list.
The following example uses the LEAST
function to return the smallest string in alphabetical order:
SELECT LEAST('A','B','C') smallest;
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
smallest
---------
A
The LEAST
function returns the letter 'A'
is the smallest value alphabetically among 'A'
, 'B'
, and 'C'
.
The following example uses the LEAST
function to compare two boolean values:
SELECT LEAST(true, false) smallest;
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
smallest
---------
f
When comparing true
and false
, true
is greater than false
so the LEAST
function returns false
.
The following example uses the LEAST
function to find the earliest date in a list of date literals:
SELECT
LEAST ('2025-01-01', '2025-02-01', '2025-03-01', NULL) earliest;
Code language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)
Output:
earliest
------------
2025-01-01
In this example, the LEAST
function returns the January 1, 2025
because it the earliest dates among January 1, 2025
, February 1 2025
, and March 1, 2025
Notice that the LEAST
function ignores NULL
in the list.
Summary #
- Use the
LEAST
function to return the smallest value in a list of values. - The
LEAST
function ignoresNULL
.