Sorted difference between two columns in MySQL?


Use ORDER BY clause for this. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,40);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(50,5);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(51,56);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(52,78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(90,7);
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 10     | 40     |
| 50     | 5      |
| 51     | 56     |
| 52     | 78     |
| 90     | 7      |
+--------+--------+
5 rows in set (0.00 sec)

Following is the query to get sorted difference between two columns −

mysql> select (Value1-Value2) as Sub from DemoTable order by Sub DESC;

Output

+------+
| Sub  |
+------+
| 83   |
| 45   |
| -5   |
| -26  |
| -30  |
+------+
5 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 12:11:55
Advertisements