SQL Geospatial Distance Calculator
Calculate the distance between two latitude and longitude points and generate the SQL code.
Calculator
3944.35 km
Generated SQL Query (PostGIS)
SELECT ST_Distance(
ST_MakePoint(-74.0060, 40.7128)::geography,
ST_MakePoint(-118.2437, 34.0522)::geography
) / 1000 AS distance_km;
Distance Comparison Chart
A comparison of the calculated distance with major global distances.
What is Calculating Distance Using Latitude and Longitude in SQL?
To calculate distance using latitude and longitude in SQL is to determine the geographical separation between two points on the Earth’s surface directly within a database query. This technique is fundamental for location-based services, logistics, and geospatial analysis. Instead of pulling coordinates into an application to perform calculations, the work is done by the database engine, which is often more efficient. The most common method for this is the Haversine formula, which calculates the great-circle distance—the shortest path between two points on a sphere. Modern SQL dialects, such as PostgreSQL with PostGIS and SQL Server, have built-in functions that abstract this complexity, making it easy to query distances.
The Haversine Formula and Mathematical Explanation
The core of most SQL distance calculations is the Haversine formula. It treats the Earth as a perfect sphere, which is accurate enough for most applications. The formula is: a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2), c = 2 ⋅ atan2(√a, √(1−a)), d = R ⋅ c. This formula is less susceptible to rounding errors for small distances compared to calculations based on the spherical law of cosines.
| Variable | Meaning | Unit | Typical Range |
|---|---|---|---|
| φ | Latitude | Radians | -π/2 to π/2 (-90° to 90°) |
| λ | Longitude | Radians | -π to π (-180° to 180°) |
| Δφ, Δλ | Difference in latitude/longitude | Radians | – |
| R | Earth’s mean radius | Kilometers | ~6,371 km |
| d | Distance between the two points | Kilometers | 0 to ~20,000 km |
Practical Examples
Example 1: Finding Nearby Stores
A retail company wants to find all stores within a 10-kilometer radius of a customer’s location (48.8566° N, 2.3522° E) for a “find my nearest store” feature. They can use a SQL query to calculate distance using latitude and longitude in SQL for every store in their database.
Example 2: Validating Delivery Range
A food delivery service needs to verify if a customer’s address is within the 5-mile delivery radius of a restaurant. When an order is placed, a quick SQL query can calculate the distance and flag orders that are out of range, preventing operational issues.
How to Use This Calculator
- Enter Coordinates: Input the latitude and longitude for Point 1 and Point 2.
- View Real-Time Results: The distance in kilometers and miles is calculated automatically.
- Get the SQL Code: The box below the results provides a ready-to-use SQL query for PostGIS, MySQL, or SQL Server.
- Copy and Use: Use the “Copy SQL” button to transfer the query to your database client.
Key Factors That Affect Distance Calculation Results
- Earth’s Shape (Ellipsoidal vs. Spherical): The Haversine formula assumes a perfect sphere, but the Earth is an oblate spheroid. For high-precision needs like aviation, a more complex formula like Vincenty’s might be necessary.
- Coordinate Precision: The number of decimal places in your latitude and longitude data significantly impacts accuracy.
- SQL Data Types: Using `FLOAT` or `DECIMAL` can affect precision. For geospatial data, native types like `geography` in SQL Server or PostGIS are best.
- Database Engine: Native functions (`ST_Distance`, `ST_Distance_Sphere`) are highly optimized and faster than manual implementations.
- SRID (Spatial Reference Identifier): Using the correct SRID, like 4326 for WGS 84, is crucial for ensuring your data is interpreted correctly.
- Indexing: Without spatial indexes, querying large datasets by distance will be very slow. A bounding box approach combined with indexing is essential for performance.
Frequently Asked Questions (FAQ)
Pythagoras’ theorem works on a flat plane. For geographical coordinates, it produces large errors because it doesn’t account for the Earth’s curvature. The Haversine formula is designed for a sphere.
The `geography` type is for round-earth calculations (latitude/longitude). The `geometry` type is for flat-plane (Euclidean) calculations. For global distance, `geography` is correct.
It’s very accurate for most purposes, with an error margin of about 0.5% due to the Earth not being a perfect sphere.
Use spatial indexes on your coordinate columns. Also, for “find nearby” queries, first filter results within a rough “bounding box” before applying the precise distance calculation.
Yes. After calculating the distance in kilometers, multiply the result by approximately 0.621371.
SRID 4326 refers to the WGS 84 spatial reference system, the standard for GPS and global coordinate data.
No, SQL functions calculate the direct “as the crow flies” distance. For road network distances, you need to use an external API like Google Maps Distance Matrix or an advanced routing engine like pgRouting for PostGIS.
PostgreSQL with the PostGIS extension is widely considered the most powerful open-source option for serious geospatial work. SQL Server and MySQL also have robust spatial capabilities.
Related Tools and Internal Resources
- SQL Spatial Functions: An In-Depth Guide – Explore a comprehensive overview of functions beyond simple distance.
- Bounding Box Query Generator – Speed up your location queries by generating efficient bounding box filters.
- Geospatial Indexing Strategies – Learn how to properly index your data for high-performance geospatial queries.
- Batch Address Distance Tool – Calculate distances for a large set of coordinates at once.
- Haversine vs. Vincenty: Which Formula to Use? – A detailed comparison for when precision matters most.
- Visualizing Geospatial Data with SQL – Learn how to extract data from your database to create maps and visualizations.