MySQL LEAST is one of the Comparison Function, which is used to return the smallest argument. This function follows below shown rules:
- If any of the argument is NULL, Least function returns NULL
- If all the arguments are integers, least finds the smallest or minimum number.
- and, If we used strings as the arguments, this function finds the minimum or smallest string.
In this article we will show you, How to find the smallest among given values in MySQL with example.
MySQL LEAST Syntax
The basic syntax of the Least in MySQL is as shown below:
LEAST(Value1, Value2......, ValueN);
MySQL LEAST Function Example 1
The following query will show multiple ways to use this MySQL Least function.
In the First statement, We used integers as arguments. The second statement finds the smallest decimal number. Next, it finds the smallest character in g, d, M and Z.
SELECT LEAST(22, 5, 10);
SELECT LEAST(12.5, 3.2, 7.0, 2.5, 9.90);
SELECT LEAST('g', 'd', 'M', 'Z');
OUTPUT
Here, we used the combinations of integer, string and decimal inside this Least function. Next, we used NULL as an argument.
SELECT LEAST('hello', 'hi', 'mysql');
SELECT LEAST(10, 10.0, '10');
SELECT LEAST(10, NULL, 20, 50);
OUTPUT
MySQL LEAST Function Example 2
In MySQL, you can use this function on column data. These example shows you, how to use this function on a table.
In general, we use this Least function to find the smallest among multiple columns. Below query shows the smallest values among the Yearly Income column and Sales column for each employee Id.
SELECT EmpID,
FirstName,
LastName,
YearlyIncome,
Sales,
LEAST(YearlyIncome, SALES)
FROM `MySQL Tutorial`.customer
OUTPUT
Above Query was displayed Sales values as output because those are the smallest among two.
This time we are comparing or finding the smallest among the Education and Occupation column values for each and every Employee ID.
SELECT EmpID,
FirstName,
LastName,
Education,
Occupation,
YearlyIncome,
Sales,
LEAST(Education, Occupation)
FROM `MySQL Tutorial`.customer
OUTPUT
Thank You for Visiting Our Blog