How to Get Max of Two Values in MySQL

Sheeraz Gul Feb 02, 2024
How to Get Max of Two Values in MySQL

This tutorial demonstrates how to get the maximum of two values using MySQL.

MySQL Max of Two Values

MySQL provides a built-in method, greatest(), solely to choose the maximum value from two values. The syntax for this method is below.

SELECT greatest(FirstValue, SecondValue);

The FirstValue and SecondValue are the values from which the maximum value will be selected. Let’s try an example.

Select greatest(500, 800);

The code for this is always a simple one-line code. Let’s see the output.

+--------------------+
| greatest(500, 800) |
+--------------------+
| 800                |
+--------------------+
1 row in set (0.00 sec)

As we can see, it selected the maximum number from the given values. But if the value is a string, let’s try an example.

Select greatest('Delftstack', 'delftstack');

Now the code above will select the max value from two given strings. See the output:

+--------------------------------------+
| greatest("Delftstack", "delftstack") |
+--------------------------------------+
| delftstack                           |
+--------------------------------------+
1 row in set (0.00 sec)

As we can see, both values are similar, with the only difference being that the first letter of the first value is capitalized. The greatest() method will calculate the maximum value of the string based on their ASCII value; in that case, the delftstack is greater than the Delftstack.

Let’s check them:

Select ascii('Delftstack');

Output:

+---------------------+
| ascii("Delftstack") |
+---------------------+
| 68                  |
+---------------------+
1 row in set (0.00 sec)

And for delftstack:

Select ascii('delftstack')

Output:

+---------------------+
| ascii("delftstack") |
+---------------------+
| 100                 |
+---------------------+
1 row in set (0.00 sec)

As we can see, the ASCII value for delftstack is greater than Delftstack; that’s why the greatest method chooses delftstack as the maximum value.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook