How to get the max of two values MySQL?


To get the maximum of two values in MySQL, we can use the predefined function “greatest”. The syntax of greatest() function is as follows −

SELECT greatest(value1,value2);

Applying the above query, To get the maximum value from two values. The query is as follows −

Case 1

We are giving both the values int.

mysql> SELECT greatest(100,-300);

After executing the above query, we will get the following output

+--------------------+
| greatest(100,-300) |
+--------------------+
| 100                |
+--------------------+
1 row in set (0.00 sec)

Case 2

We are giving both the values string −

The query is as follows −

mysql> SELECT greatest('A','a');

The following is the output −

+-------------------+
| greatest('A','a') |
+-------------------+
| a                 |
+-------------------+
1 row in set (0.00 sec)

Here you can see ‘a’ is displayed. This is because the ASCII value of ‘a’ is 97 and ‘A’ is 65. Therefore, the value 97 is greater than 65, that means ’a’ is greater than ‘A’.

Let us check now. The query for ‘a’ −

mysql> SELECT ascii('a');

Here is the output

+------------+
| ascii('a') |
+------------+
| 97         |
+------------+
1 row in set (0.00 sec)

The query for ‘A’.

mysql> SELECT ascii('A');

The following is the output

+------------+
| ascii('A') |
+------------+
| 65         |
+------------+
1 row in set (0.00 sec)

Updated on: 24-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements