Skip to content

Instantly share code, notes, and snippets.

@jrwarwick
Created December 2, 2022 16:23
Show Gist options
  • Save jrwarwick/229bdfc1d56a5dfa859bcca2a95cafcd to your computer and use it in GitHub Desktop.
Save jrwarwick/229bdfc1d56a5dfa859bcca2a95cafcd to your computer and use it in GitHub Desktop.
Simple Oracle SQL haversine distance calculation
-- Simple Oracle SQL haversine distance.
-- Most likely you will want to put this into a CTE.
-- Not suitable for high-accuracy. Answer will be in km.
-- Still requires sdo for at least the degrees to radians conversion.
SELECT descript, ( /* Approx. Earth radius in km:*/ 6371 * acos(
cos(SDO_UTIL.CONVERT_UNIT(Lat1, 'Degree', 'Radian')) *
cos(SDO_UTIL.CONVERT_UNIT(Lat2, 'Degree', 'Radian')) *
cos(SDO_UTIL.CONVERT_UNIT(Lon2, 'Degree', 'Radian') - SDO_UTIL.CONVERT_UNIT(Lon1, 'Degree', 'Radian') )
+ sin(SDO_UTIL.CONVERT_UNIT(Lat1, 'Degree', 'Radian')) * sin(SDO_UTIL.CONVERT_UNIT(Lat2, 'Degree', 'Radian'))
)) AS haversine_distance
FROM (
select
'smithsonian to kenedy space center ~ 1195km' descript,
38.88978542398205 lat1, -77.02088373582937 lon1,
28.651877187556792 lat2, -80.68296750105196 lon2
from dual
UNION
select
'walk across the goldengate bridge ~ 1.7k' descript,
37.810545958442475 lat1, -122.47710002669695 lon1,
37.826268071897346 lat2, -122.47902012968235 lon2
from dual
) some_table_with_lat_longs_as_simple_numbers
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment