MySQL GREATEST Function

MySQL GREATEST is one of the Comparison Function, which returns the largest argument. This MySQL GREATEST function follows below rules:

  • If any of the argument is NULL, this function returns NULL
  • If all the arguments are integers, it finds the maximum number.
  • And, if we used strings as the arguments, the Greatest function finds the maximum or greatest string.

In this section, we show you how to find the greatest among given values in MySQL with example.

MySQL GREATEST Syntax

The basic syntax of the Greatest in MySQL is as shown below:

GREATEST(Value1, Value2......, ValueN);

MySQL GREATEST Function Example 1

The following query shows multiple ways to use this MySQL Greatest function. First, We used integers as arguments. The second statement finds the maximum decimal number. Next, it finds the greatest character in g, t, d, and o.

SELECT GREATEST(20, 25, 10);

SELECT GREATEST(2.0, 3.2, 1.0, 2.5, 1.90);

SELECT GREATEST('g', 't', 'd', 'o');
MySQL GREATEST Function 1

Here, we used the combinations of string, integer, and decimal. Next, we used NULL as the MySQL argument.

SELECT GREATEST('tutorialgateway', 'mysql', 'oracle');

SELECT GREATEST(10, '10', 10.0);

SELECT GREATEST(10, 20, NULL);
MySQL GREATEST Function 2

MySQL GREATEST Function Example 2

In MySQL, you can use this function on column data. This example shows you how to use this function in a where clause. Here, it returns all the records whose Yearly Income is greater than 70000.

SELECT EmpID, 
FirstName,
      LastName,
      Occupation,
      YearlyIncome,
      Sales,
      HireDate
FROM `MySQL Tutorial`.customer
WHERE YearlyIncome > GREATEST(50000, 70000, 60000);
MySQL GREATEST Function 3

In general, we use this Greatest function to find the greatest among multiple columns (not the rows). The below query shows the Greatest among the Yearly Income column and Sales column for each employee Id.

SELECT EmpID,
FirstName,
      LastName,
      YearlyIncome,
      Sales, 
GREATEST(YearlyIncome, SALES)
FROM `MySQL Tutorial`.customer
MySQL GREATEST Function 4

The above query was displayed yearly income values as output because those are the greatest.

This time we are comparing or finding the greatest among the Education and Occupation column values for every Employee ID.

SELECT EmpID, 
FirstName,
      LastName,
      Education,
      Occupation,
      YearlyIncome,
      Sales,
GREATEST(Education, Occupation)
FROM `MySQL Tutorial`.customer
MySQL GREATEST Function 5