How to order by the highest value from two columns in MySQL?


Let us first create a table −

mysql> create table DemoTable834(
   Value1 int,
   Value2 int
);
Query OK, 0 rows affected (1.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable834 values(10,20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable834 values(40,50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable834 values(20,24);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable834 values(30,10);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable834;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |     20 |
|     40 |     50 |
|     20 |     24 |
|     30 |     10 |
+--------+--------+
4 rows in set (0.00 sec)

Following is the query to order by the highest value from two columns using GREATEST() −

mysql> select *from DemoTable834
order by greatest(Value1,Value2) DESC;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     40 |     50 |
|     30 |     10 |
|     20 |     24 |
|     10 |     20 |
+--------+--------+
4 rows in set (0.00 sec)

Updated on: 03-Sep-2019

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements