The LEAST() function in MySQL is used to return the smallest (least) value from a list of arguments. It evaluates each argument and returns the one with the lowest value.
Syntax
LEAST(arg1, arg2, arg3, ...)
Definition and Usage
- The
LEAST()function compares two or more values and returns the smallest value in the list. - If any argument is
NULL, the result will beNULL. - The function works for numeric, string, and date types, but the comparison is done based on the data type and the values' order.
Parameter Values
| Parameter | Description |
|---|---|
arg1, arg2, arg3, ... |
Required. A list of arguments to be compared. These can be numbers, strings, or dates. |
Technical Details
- Works in: From MySQL 4.0
- Return Value: The smallest value from the list of arguments.
Examples
Example 1: Return the smallest value of a list of numbers
SELECT LEAST(3, 12, 34, 8, 25);
Result:
LEAST(3, 12, 34, 8, 25): 3
Explanation: The function returns 3, which is the smallest number in the list.
Example 2: Return the smallest value from a list of strings
SELECT LEAST("w3Schools.com", "microsoft.com", "apple.com");
Result:
LEAST("w3Schools.com", "microsoft.com", "apple.com"): "apple.com"
Explanation: The function compares the strings lexicographically (alphabetically) and returns "apple.com" as it comes first in alphabetical order.
Example 3: Return the smallest date value
SELECT LEAST('2024-12-01', '2024-12-15', '2024-12-10');
Result:
LEAST('2024-12-01', '2024-12-15', '2024-12-10'): '2024-12-01'
Explanation: The function returns '2024-12-01' as it is the earliest date.
Usage Notes
- The
LEAST()function is useful for selecting the minimum value from multiple expressions or columns. - When dealing with strings, it compares them in lexicographical order.
- For date values, the function returns the earliest date.
- If any argument is
NULL, the result will beNULL, so it's often good practice to ensure thatNULLvalues are handled properly usingIFNULL()orCOALESCE().
This function is commonly used for finding the smallest value in a set of values, such as finding the minimum salary, date, or number from a collection of records.