Write sql code to calculate distance between latitude and longitude coordinates
- User
Write sql code to calculate distance between latitude and longitude coordinates
- Assistantsql
-- Calculate distance between two points using the Haversine formula SELECT SQRT( POW( (RADIANS(latitude2) - RADIANS(latitude1)), 2 ) + COS(RADIANS(latitude1)) * COS(RADIANS(latitude2)) * POW( (RADIANS(longitude2) - RADIANS(longitude1)), 2 ) ) * 6371 AS distance_km FROM your_table WHERE -- Specify your conditions here, e.g., point_id = 123; -- Replace the following with your actual column names: -- latitude1, longitude1: Coordinates of the first point -- latitude2, longitude2: Coordinates of the second point -- your_table: The name of your table containing the coordinates -- Note: -- This formula assumes the Earth is a perfect sphere. -- The result is in kilometers. -- Adjust the multiplier (6371) if you need distance in miles or other units.Explanation:
-
Haversine Formula: This SQL code implements the Haversine formula, a widely used method for calculating distances between two points on a sphere given their longitudes and latitudes.
-
Radians Conversion: The
RADIANS()function converts the latitude and longitude values from degrees to radians, which is required by the trigonometric functions used in the formula. -
Distance Calculation: The formula calculates the square of the chord length between the two points on the sphere's surface.
-
Square Root: The
SQRT()function takes the square root of the result to obtain the actual distance. -
Earth Radius: The value
6371represents the Earth's radius in kilometers. Multiplying the result by this value gives the distance in kilometers. -
Customization:
- Replace
latitude1, , , and with the actual column names in your table containing the coordinates.
- Replace
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.