How to Use the LEAST() Function in MySQL

08/05/2021

Contents

In this article, you will learn how to use the LEAST() function in MySQL.

Using the LEAST() function in MySQL

The LEAST() function in MySQL is used to retrieve the smallest value from a list of expressions.

Syntax

The basic syntax of the LEAST() function in MySQL is as follows:

LEAST(value1, value2, ...., value_n)

The LEAST() function accepts a list of one or more expressions or column names separated by commas as parameters. The LEAST() function returns the smallest value from the list of expressions.

Examples

Using LEAST() with numeric values

Suppose we have a table called “employees” that contains the following data:

+----+----------+-------+--------+
| id | name     | salary| bonus  |
+----+----------+-------+--------+
| 1  | John     | 30000 | 5000   |
| 2  | Mary     | 25000 | 7000   |
| 3  | David    | 35000 | 2000   |
| 4  | Jennifer | 40000 | 4000   |
+----+----------+-------+--------+

Now, if we want to find the employee who has the smallest salary and bonus, we can use the LEAST() function as follows:

SELECT name, LEAST(salary, bonus) as lowest
FROM employees;

Output:

+----------+--------+
| name     | lowest |
+----------+--------+
| John     | 30000  |
| Mary     | 25000  |
| David    | 2000   |
| Jennifer | 4000   |
+----------+--------+

In the above example, we have used the LEAST() function to find the employee who has the smallest salary and bonus.

Using LEAST() with strings

Suppose we have a table called “students” that contains the following data:

+----+---------+---------+
| id | name    | grade   |
+----+---------+---------+
| 1  | John    | A       |
| 2  | Mary    | B       |
| 3  | David   | C       |
| 4  | Jennifer| D       |
+----+---------+---------+

Now, if we want to find the student who has the lowest grade, we can use the LEAST() function as follows:

SELECT name, LEAST(grade) as lowest
FROM students;

Output:

+----------+--------+
| name     | lowest |
+----------+--------+
| John     | A      |
| Mary     | B      |
| David    | C      |
| Jennifer | D      |
+----------+--------+

In the above example, we have used the LEAST() function to find the student who has the lowest grade.