Fetch maximum value from multiple columns with null and non-null values?

MySQLMySQLi Database

For this, you can use COALESCE(). For the maximum value, use GREATEST() in MySQL. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int,
   -> Value3 int
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(NULL,80,76);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(NULL,NULL,100);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(56,NULL,45);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(56,120,90);
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|   NULL |     80 |     76 |
|   NULL |   NULL |    100 |
|     56 |   NULL |     45 |
|     56 |    120 |     90 |
+--------+--------+--------+
4 rows in set (0.00 sec)

Following is the query to fetch the maximum value from multiple columns −

mysql> select greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) from DemoTable;

This will produce the following output −

+--------------------------------------------------------------------+
| greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) |
+--------------------------------------------------------------------+
|                                                                 80 |
|                                                                100 |
|                                                                 56 |
|                                                                120 |
+--------------------------------------------------------------------+
4 rows in set (0.00 sec)
raja
Published on 17-Dec-2019 10:09:49
Advertisements