MySQL query to sort increasing the difference between n and the value in the table?


For sort by distance, use ORDER BY ABS(). Let us first create a table −

mysql> create table DemoTable
(
   Number int
);
Query OK, 0 rows affected (1.16 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.51 sec)
mysql> insert into DemoTable values(101);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(102);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable values(103);
Query OK, 1 row affected (0.84 sec)
mysql> insert into DemoTable values(104);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(105);
Query OK, 1 row affected (0.73 sec)
mysql> insert into DemoTable values(106);
Query OK, 1 row affected (0.95 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
|    100 |
|    101 |
|    102 |
|    103 |
|    104 |
|    105 |
|    106 |
+--------+
7 rows in set (0.00 sec)

Following is the query to sort by distance. Here, n is 103 −

mysql> select *from DemoTable order by abs(103-Number);

This will produce the following output −

+--------+
| Number |
+--------+
|    103 |
|    102 |
|    104 |
|    101 |
|    105 |
|    100 |
|    106 |
+--------+
7 rows in set (0.17 sec)

Updated on: 04-Oct-2019

48 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements