Skip to content

Instantly share code, notes, and snippets.

@bentappin
Last active August 29, 2015 14:02
Show Gist options
  • Save bentappin/106cebae2bb613638cac to your computer and use it in GitHub Desktop.
Save bentappin/106cebae2bb613638cac to your computer and use it in GitHub Desktop.
SQL: Sort by distance from a point
# 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