MySQL GREATEST Function

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

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

In this section, we show you how to find the greatest among given values with an example and the basic syntax of the MySQL Greatest function is as shown below:

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

MySQL GREATEST Function Example

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 largest 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');
GREATEST Value Example from Command Prompt 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

GREATEST Example 2

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

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

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

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

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

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 customer
MySQL GREATEST Function 5