Order by a function of two columns in a single MySQL query

MySQLMySQLi Database

Let us first create a table

mysql> create table orderByAFunctionDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstNumber int,
   -> SecodNumber int
   -> );
Query OK, 0 rows affected (0.44 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(10,4);
Query OK, 1 row affected (0.11 sec)
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(45,78);
Query OK, 1 row affected (0.17 sec)
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(23,10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(67,237);
Query OK, 1 row affected (0.16 sec)
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(12,90);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from orderByAFunctionDemo;

The following is the output

+----+-------------+-------------+
| Id | FirstNumber | SecondNumber|
+----+-------------+-------------+
|  1 |          10 |           4 |
|  2 |          45 |          78 |
|  3 |          23 |          10 |
|  4 |          67 |         237 |
|  5 |          12 |          90 |
+----+-------------+-------------+
5 rows in set (0.00 sec)

Here is the query to order by a function of two columns. The query is as follows −

mysql> select (4*FirstNumber+5*SecondNumber) as Calculation
   -> from orderByAFunctionDemo
   -> order by Calculation desc;

The following is the output

+-------------+
| Calculation |
+-------------+
|        1453 |
|         570 |
|         498 |
|         142 |
|          60 |
+-------------+
5 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 12:22:52
Advertisements