Skip to content
Advertisement

Order by a subtraction expression sql

I would like to perform an ORDER BY in sql that sorts the returned rows by their distance from my integer of interest. The expression would be ORDER BY (constant - ColumnName) ASC specifically, something like ORDER BY (10 - Distance) ASC. When I tried running this expression the distances were just sorted descending which is not what I am looking for.

Is this possible in sql?

Advertisement

Answer

“Distance from integer of interest” suggests that you want abs():

ORDER BY ABS(constant - ColumnName) ASC

You are correct that the following are equivalent:

ORDER BY 10 - Distance
ORDER BY Distance DESC
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement