Select maximum of sum of two columns in MySQL

MySQLMySQLi Database

To select maximum of sum of two columns, use aggregate function MAX() along with subquery. Let us first create a table −

mysql> create table DemoTable1587
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1587 values(30,50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1587 values(80,90);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1587 values(40,67);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1587;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     30 |     50 |
|     80 |     90 |
|     40 |     67 |
+--------+--------+
3 rows in set (0.00 sec)

Here is the query to select maximum of sum of two columns −

mysql> select * from DemoTable1587
  -> where Value1+Value2=( select max(Value1+Value2) from DemoTable1587);

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     80 |     90 |
+--------+--------+
1 row in set (0.03 sec)
raja
Published on 16-Dec-2019 06:40:35
Advertisements