Get MySQL maximum value from 3 different columns?

MySQLMySQLi Database

To get the maximum value from three different columns, use the GREATEST() function.

The syntax is as follows

SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table MaxOfThreeColumnsDemo
   -> (
   -> First int,
   -> Second int,
   -> Third int
   -> );
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into MaxOfThreeColumnsDemo values(30,90,60);
Query OK, 1 row affected (0.16 sec)
mysql> insert into MaxOfThreeColumnsDemo values(100,40,50);
Query OK, 1 row affected (0.20 sec)
mysql> insert into MaxOfThreeColumnsDemo values(101,290,150);
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from MaxOfThreeColumnsDemo;

The following is the output

+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
| 30    | 90     | 60    |
| 100   | 40     | 50    |
| 101   | 290    | 150   |
+-------+--------+-------+
3 rows in set (0.00 sec)

Here is the query to find the greatest of three columns

mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo;

The following is the output

+------------------------+
| MAXValueOfThreeColumns |
+------------------------+
| 90                     |
| 100                    |
| 290                    |
+------------------------+
3 rows in set (0.00 sec)
raja
Published on 29-Mar-2019 15:04:59
Advertisements