Write sql code to calculate distance between latitude and longitude coordinates
- User
Write sql code to calculate distance between latitude and longitude coordinates
Assistant
Calculating the distance between two points on the Earth's surface given their latitude and longitude coordinates can be accomplished using the Haversine formula in SQL. The Haversine formula gives the great-circle distance between two points on a sphere (such as the Earth) given their longitudes and latitudes. Here is a basic SQL function that implements the Haversine formula to calculate the distance in kilometers and miles between two points defined by their latitude and longitude coordinates.
Please note, this example is written in a generic SQL style that should be adaptable to most SQL databases with minor adjustments (e.g., function declaration syntax might vary between MySQL, PostgreSQL, SQL Server, etc.). For this example, I'll provide the function in a style closely matching PostgreSQL, with notes on how to adapt it for MySQL and SQL Server.
PostgreSQL Example
sqlCREATE OR REPLACE FUNCTION calculate_distance( lat1 numeric, lon1 numeric, lat2 numeric, lon2 numeric ) RETURNS TABLE (distance_km numeric, distance_miles numeric) AS $$ BEGIN -- Radius of the Earth in km and miles RETURN QUERY WITH -- Convert lat/lon to radians coordinates AS ( SELECT lat1 * PI() / 180 AS lat1_rad, lon1 * PI() / 180 AS lon1_rad, lat2 * PI() / 180 AS lat2_rad, lon2 * PI() / 180 AS lon2_rad ), -- Calculate differences in latitude and longitude differences AS ( SELECT lat2_rad - lat1_rad AS dlat, lon2_rad - lon1_rad AS dlon FROM coordinates ), -- Apply the Haversine formula haversine AS ( SELECT POWER(SIN(dlat/2), 2) + COS(lat1_rad) * COS(lat2_rad) * POWER(SIN(dlon/2), 2) AS a, 2 * ATAN2(SQRT(a), SQRT(1-a)) AS c FROM coordinates CROSS JOIN differences ) -- Calculate distances using Earth's radius SELECT 6371 * c AS distance_km, -- kilometers 3959 * c AS distance_miles -- miles FROM haversine; END; $$ LANGUAGE plpgsql; -- Example usage: SELECT * FROM calculate_distance(52.5200, 13.4050, 48.8566, 2.3522);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.