In MariaDB, LEAST()
is a built-in function that returns the least (i.e. smallest/minimum-valued) argument from its list of arguments.
To get the greatest value, use GREATEST()
.
Syntax
The syntax goes like this:
LEAST(value1,value2,...)
Where value1,value2,…
is two or more arguments for which to return the smallest/minimum-valued.
Example
Here’s an example:
SELECT LEAST(3, 8);
Result:
+-------------+ | LEAST(3, 8) | +-------------+ | 3 | +-------------+
Here’s another example that uses more arguments:
SELECT LEAST(10, 7, 9, 12, 80, 8, 14);
Result:
+--------------------------------+ | LEAST(10, 7, 9, 12, 80, 8, 14) | +--------------------------------+ | 7 | +--------------------------------+
Expressions
The arguments can include expressions like this:
SELECT LEAST(2 * 3, 1 * 3);
Result:
+---------------------+ | LEAST(2 * 3, 1 * 3) | +---------------------+ | 3 | +---------------------+
Strings
The arguments don’t need to be numeric. For example, here’s a comparison of strings:
SELECT LEAST('a', 'b', 'c');
Result:
+----------------------+ | LEAST('a', 'b', 'c') | +----------------------+ | a | +----------------------+
Dates
Here’s a comparison of date strings:
SELECT LEAST('2020-01-01', '2021-01-01');
Result:
+-----------------------------------+ | LEAST('2020-01-01', '2021-01-01') | +-----------------------------------+ | 2020-01-01 | +-----------------------------------+
Mixed Types
The MariaDB documentation states that if any argument is a case-sensitive string, the arguments are compared as case-sensitive strings. However, you may find that mixing types can produce unexpected results, and a warning.
Example:
SELECT LEAST('Cat', 10);
Result:
+------------------+ | LEAST('Cat', 10) | +------------------+ | 0 | +------------------+ 1 row in set, 1 warning (0.000 sec)
Check the warning:
SHOW WARNINGS;
Result:
+---------+------+-----------------------------------------+ | Level | Code | Message | +---------+------+-----------------------------------------+ | Warning | 1292 | Truncated incorrect DOUBLE value: 'Cat' | +---------+------+-----------------------------------------+
Null Arguments
LEAST()
returns null
if any argument is null
:
SELECT LEAST(1, null, 3);
Result:
+-------------------+ | LEAST(1, null, 3) | +-------------------+ | NULL | +-------------------+
Missing Arguments
Calling LEAST()
with the wrong number of arguments, or without any arguments results in an error:
SELECT LEAST();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'LEAST'
And:
SELECT LEAST(10);
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'LEAST'