MySQL query to display records ordered by numeric difference?


Use ORDER BY and set the difference to display records ordered by numeric difference. Following is the syntax −

select *from yourTableName
order by (yourIntegerColumnName1 - yourIntegerColumnName2);

Let us first create a table −

mysql> create table DemoTable1313
-> (
-> Name varchar(20),
-> Score1 int,
-> Score2 int
-> );
Query OK, 0 rows affected (3.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1313 values('Chris',40,60);
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1313 values('David',70,50);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1313 values('Adam',35,30);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1313;

Output

+-------+--------+--------+
| Name  | Score1 | Score2 |
+-------+--------+--------+
| Chris |     40 |     60 |
| David |     70 |     50 |
| Adam  |     35 |     30 |
+-------+--------+--------+
3 rows in set (0.00 sec)

Following is the query to order by numeric difference −

mysql> select *from DemoTable1313
-> order by (Score1-Score2);

Output

+-------+--------+--------+
| Name | Score1  | Score2 |
+-------+--------+--------+
| Chris | 40     |    60  |
| Adam  | 35     |    30  |
| David | 70     |    50  |
+-------+--------+--------+
3 rows in set (0.00 sec)

Updated on: 04-Nov-2019

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements