Can we order a MySQL result with mathematical operations?


Yes, we can order with mathematical operations using ORDER BY clause. Let us first create a table:

mysql> create table orderByMathCalculation
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Quantity int,
   -> Price int
   -> );
Query OK, 0 rows affected (0.57 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into orderByMathCalculation(Quantity,Price) values(10,50);
Query OK, 1 row affected (0.21 sec)

mysql> insert into orderByMathCalculation(Quantity,Price) values(20,40);
Query OK, 1 row affected (0.14 sec)

mysql> insert into orderByMathCalculation(Quantity,Price) values(2,20);
Query OK, 1 row affected (0.13 sec)

mysql> insert into orderByMathCalculation(Quantity,Price) values(11,10);
Query OK, 1 row affected (0.24 sec)

Following is the query to display all records from the table using select statement:

mysql> select *from orderByMathCalculation;

This will produce the following output

+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 1  | 10       | 50    |
| 2  | 20       | 40    |
| 3  | 2        | 20    |
| 4  | 11       | 10    |
+----+----------+-------+
4 rows in set (0.00 sec)

Case 1: Here is the query to do order by mathematical operations in ascending order.

mysql> select *from orderByMathCalculation order by Quantity*Price;

This will produce the following output

+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 3  | 2        | 20    |
| 4  | 11       | 10    |
| 1  | 10       | 50    |
| 2  | 20       | 40    |
+----+----------+-------+
4 rows in set (0.00 sec)

Case 1: Here is the query to do order by mathematical operations in descending order.

mysql> select *from orderByMathCalculation order by Quantity*Price desc;

This will produce the following output

+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 2  | 20       | 40    |
| 1  | 10       | 50    |
| 4  | 11       | 10    |
| 3  | 2        | 20    |
+----+----------+-------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements