MySQL LEAST is one of the Comparison Function, which returns the smallest argument. This MySQL LEAST function follows below shown rules:
- If any of the argument is NULL, it returns NULL.
- If all the arguments are integers, it 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 show you how to find the smallest among given values with example.
MySQL LEAST Syntax
The basic syntax of the MySQL Least Function is as shown below:
LEAST(Value1, Value2......, ValueN);
MySQL LEAST Function Example 1
The following query shows 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');
Here, we used the combinations of integer, string, and decimal inside this Least function. Next, we used NULL as the MySQL argument.
SELECT LEAST('hello', 'hi', 'mysql');
SELECT LEAST(10, 10.0, '10');
SELECT LEAST(10, NULL, 20, 50);
MySQL LEAST Function Example 2
W can use this function on column data. This example shows you how to use this function on a table.
In general, we use this function to find the smallest among multiple columns. The 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 customer
The 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 Employee ID.
SELECT EmpID, FirstName, LastName, Education, Occupation, YearlyIncome, Sales, LEAST(Education, Occupation) FROM customer