MySQL query to sort multiple columns together in a single query

MySQLMySQLi Database

To sort multiple columns, use ORDER BY GREATEST(). Let us first create a −

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

Insert some records in the table using insert −

mysql> insert into DemoTable1395 values(40,50,60);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1395 values(90,56,80);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1395 values(10,20,30);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select −

mysql> select * from DemoTable1395;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     40 |     50 |     60 |
|     90 |     56 |     80 |
|     10 |     20 |     30 |
+--------+--------+--------+
3 rows in set (0.00 sec)

Here is the query to sort multiple columns−

mysql> select * from DemoTable1395
    -> order by greatest(Value1,Value2,Value3);

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     10 |     20 |     30 |
|     40 |     50 |     60 |
|     90 |     56 |     80 |
+--------+--------+--------+
3 rows in set (0.00 sec)
raja
Published on 11-Nov-2019 15:04:09
Advertisements