Last active
August 29, 2015 14:02
-
-
Save bentappin/106cebae2bb613638cac to your computer and use it in GitHub Desktop.
SQL: Sort by distance from a point
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adapted from: http://dillieodigital.wordpress.com/2011/06/16/sorting-latitudelongitude-positions-by-distance-in-sql/ | |
SELECT | |
*, 6378 * 2 * ASIN( | |
SQRT( | |
POWER( | |
SIN((51.5081 - latitude) * pi() / 180 / 2), | |
2 | |
) + COS(51.5081 * pi() / 180) * COS(latitude * pi() / 180) * POWER( | |
SIN((0.1281 - longitude) * pi() / 180 / 2), | |
2 | |
) | |
) | |
) AS distance_km | |
FROM | |
my_table | |
ORDER BY | |
distance_km; | |
# PostgreSQL: distance_km ASC NULLS LAST; | |
# MySQL: -distance_km DESC; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment