Ben
Ben

Reputation: 4279

ORDER BY distance to another value

Lets say we have a table like that

id|value
--------
1 | 50
2 | 19
3 | 100
4 | 21
5 | -10

How can I use ORDER BY operator to order values by their distance to another value?

SELECT * FROM table ORDER BY nearest(value,30) DESC

To get this table:

id|value
--------
4 | 21
1 | 50
2 | 19
5 | -10
3 | 100

Upvotes: 2

Views: 510

Answers (2)

Luc M
Luc M

Reputation: 17314

Not sure that all sql dialect accepts answer of Paul92.

Here is another solution:

SELECT * 
FROM (
   SELECT 
      t.*, 
      abs(value - 30) AS abs_value
   FROM table t 
) temp
ORDER BY abs_value 

Upvotes: 2

Paul92
Paul92

Reputation: 9062

You may use:

SELECT * FROM table ORDER BY abs(value - 30) ASC

Upvotes: 5

Related Questions