Query that sorts rows as per given latitude longitude. Sort by near to far location
Asked
Active
Viewed 107 times
0
-
Please **[edit]** your question (by clicking on the [edit] link below it) and add some sample data and the expected output based on that data as [formatted text](https://meta.stackoverflow.com/a/251362). See [here](https://meta.stackexchange.com/questions/81852) for some tips on how to create nice looking text tables. ([edit] your question - do **not** put code or additional information in comments) – Feb 13 '23 at 12:38
-
Does this answer your question? [Sort by proximity after getting distance using pythagoras - postgresql](https://stackoverflow.com/questions/74477571/sort-by-proximity-after-getting-distance-using-pythagoras-postgresql) – Richard Hansell Feb 13 '23 at 13:39
-
1Don't use Pythagoras formula on lat-longs, it is plain **wrong** as a degree of latitude doesn't have the same ground length, in meters, as a degree of longitude (@RichardHansell, @SQLpro). Instead you can Postgis and the operator `<->` on geographies (NOT on lat-long geometries), or you can compute the distance yourself using the haversine formula. – JGH Feb 13 '23 at 14:24
1 Answers
0
From a point like A (lat = 3, long = 2), you can use ORDER BY like this :
ORDER BY SQRT(SQUARE((lat-latitude) + SQUARE((long-longitude))
But it would be much more smart if you use spatial functions like ST_Distance

SQLpro
- 3,994
- 1
- 6
- 14