SQL Server Latitude/Longitude Distance Calculator
e.g., 40.7128 for New York
e.g., -74.0060 for New York
e.g., 34.0522 for Los Angeles
e.g., -118.2437 for Los Angeles
Generated T-SQL Code
Here is the SQL code to perform this calculation directly in SQL Server.
Using Native GEOGRAPHY Type (Recommended)
Using Manual Haversine Formula
Distance Comparison Chart
What is Calculating Distance with Latitude and Longitude in SQL Server?
To calculate distance using latitude and longitude in SQL Server refers to the process of determining the real-world distance between two geographical points on the Earth’s surface using database functions. This is a common requirement in logistics, location-based services, geographic information systems (GIS), and any application that deals with spatial data. SQL Server provides powerful built-in tools, primarily the geography data type and its associated methods like STDistance(), to make this task efficient and accurate without needing to write complex mathematical formulas from scratch.
Instead of treating the Earth as a flat plane, the geography data type accounts for the planet’s ellipsoidal shape, providing highly accurate “as-the-crow-flies” distance calculations. This is far superior to simplistic Pythagorean calculations which are inaccurate over anything but very short distances. For anyone working with location data in a Microsoft SQL environment, understanding how to leverage these native capabilities is a critical skill for building powerful, location-aware applications.
The SQL Server Distance Calculation Formula and Explanation
While you can manually implement the Haversine formula, the most efficient and recommended method in modern SQL Server (2008 and newer) is to use the native geography data type and its built-in STDistance() method.
1. The Native STDistance() Method
This method calculates the shortest distance between two geography instances. The result is returned in meters by default, based on the SRID (Spatial Reference Identifier) used. For GPS coordinates, the standard SRID is 4326.
DECLARE @point1 geography = geography::Point(Lat1, Lon1, 4326);
DECLARE @point2 geography = geography::Point(Lat2, Lon2, 4326);
SELECT @point1.STDistance(@point2) / 1000.0 AS DistanceInKM;
2. Manual Haversine Formula (T-SQL User-Defined Function)
Before native spatial types were available, developers had to implement the Haversine formula manually. This formula calculates the great-circle distance between two points on a sphere. While the native method is preferred, it’s useful to understand the underlying math.
| Variable | Meaning | Unit | Typical Range |
|---|---|---|---|
@lat1, @lon1 |
Latitude/Longitude of Point 1 | Degrees | -90 to 90 (Lat), -180 to 180 (Lon) |
@lat2, @lon2 |
Latitude/Longitude of Point 2 | Degrees | -90 to 90 (Lat), -180 to 180 (Lon) |
R |
Earth’s Radius | Kilometers or Miles | ~6371 (km) or ~3959 (miles) |
Result |
Calculated Distance | Kilometers or Miles | 0 to ~20000 km |
Practical Examples
Example 1: New York to Los Angeles
Let’s calculate the distance between New York City (40.7128°, -74.0060°) and Los Angeles (34.0522°, -118.2437°).
- Inputs: Lat1=40.7128, Lon1=-74.0060, Lat2=34.0522, Lon2=-118.2437
- SQL:
SELECT geography::Point(40.7128, -74.0060, 4326).STDistance(geography::Point(34.0522, -118.2437, 4326)) / 1000.0; - Result: Approximately 3944 kilometers.
Example 2: London to Tokyo
Now, a longer distance between London (51.5074°, -0.1278°) and Tokyo (35.6895°, 139.6917°).
- Inputs: Lat1=51.5074, Lon1=-0.1278, Lat2=35.6895, Lon2=139.6917
- SQL:
SELECT geography::Point(51.5074, -0.1278, 4326).STDistance(geography::Point(35.6895, 139.6917, 4326)) / 1000.0; - Result: Approximately 9593 kilometers.
You may also be interested in our SQL Server spatial data guide for more complex queries.
How to Use This SQL Distance Calculator
- Enter Coordinates: Input the latitude and longitude for your two points into the designated fields. Use negative numbers for South latitudes and West longitudes.
- Select Units: Choose your desired unit of distance from the dropdown menu (Kilometers, Miles, or Nautical Miles).
- View Real-Time Results: The primary result is updated instantly as you type.
- Get the SQL Code: The calculator automatically generates two T-SQL code snippets. The first uses the modern
geography::PointandSTDistance()method, which is recommended for most use cases. The second provides a user-defined function for the manual Haversine calculation. - Copy and Use: Click the “Copy SQL Code” button to copy the recommended native T-SQL code to your clipboard for use in SQL Server Management Studio (SSMS) or your application code.
Key Factors That Affect SQL Distance Calculations
- Data Type Choice (
geographyvs.geometry):geographyis for round-earth (ellipsoidal) calculations like lat/lon points.geometryis for flat-plane (Euclidean) systems and would give incorrect results for global distances. - Spatial Indexing: For large datasets, a spatial index on the geography column is critical. Without one, SQL Server must calculate the distance for every row in the table, leading to very slow query performance.
- SRID (Spatial Reference Identifier): The SRID defines the coordinate system. For GPS data (latitude/longitude), you must use SRID 4326. Using a mismatched or incorrect SRID will cause errors or wildly inaccurate results.
- Formula Accuracy: The native
STDistance()method uses a model of the Earth that is more accurate than a perfect sphere, which is what the basic Haversine formula assumes. For most applications, the difference is negligible, butSTDistanceis technically superior. - Input Precision: The precision of your input latitude and longitude values will directly affect the precision of the output. Using a data type like
DECIMAL(9, 6)is common for storing coordinates. - Performance of UDFs: Wrapping the calculation in a scalar user-defined function (UDF) can make queries slower, as the function must be called for each row. Using
STDistance()directly in the query or with a spatial index is generally a better approach for SQL distance calculation performance.
Frequently Asked Questions (FAQ)
1. Which is better: STDistance() or a manual Haversine formula in SQL Server?
STDistance() on a geography data type is almost always better. It’s more accurate, easier to write and read, and can be heavily optimized with spatial indexes for massive performance gains. You should only use a manual formula if you are on a very old version of SQL Server (before 2008).
2. Why does STDistance() return such a large number?
By default, STDistance() returns the distance in meters, because that is the base unit for the SRID 4326. To convert to kilometers, divide the result by 1000. To get miles, divide by 1609.34.
3. What is SRID 4326 and why is it important?
SRID stands for Spatial Reference Identifier. 4326 is the specific ID for the World Geodetic System 1984 (WGS 84), the standard used by GPS. You must specify this SRID when creating geography points from lat/lon values to ensure SQL Server interprets them correctly. You can learn more about SRID 4326 explained here.
4. How do I improve performance when searching for points within a certain radius?
Create a spatial index on your geography column. This allows SQL Server to quickly eliminate points that are too far away without having to run the expensive distance calculation on every single row in your table.
5. Does the order of points matter in STDistance()?
No. @point1.STDistance(@point2) will return the exact same result as @point2.STDistance(@point1).
6. What’s the correct order for Point creation: Lat/Lon or Lon/Lat?
This is a common point of confusion. For the `geography::Point` method, the order is `geography::Point(Latitude, Longitude, SRID)`. However, in other standards like Well-Known Text (WKT), the order is often Longitude then Latitude. Always double-check the documentation for the specific function you’re using.
7. Can I calculate driving distance with these functions?
No. These functions calculate the direct, straight-line (“as-the-crow-flies”) distance. Calculating driving distance requires complex road network data and routing algorithms, which are typically handled by specialized APIs like Google Maps, not directly within SQL Server.
8. What data types should I use to store latitude and longitude?
Using DECIMAL(9, 6) or FLOAT are common and good choices. DECIMAL provides fixed precision, which can be better for financial or scientific data, while FLOAT offers a wider range but with potential for tiny rounding errors. For the best performance and functionality, store the data directly in a geography column type.
Related Tools and Internal Resources
Explore other tools and guides that might be helpful for your database and development needs.
- SQL Query Formatter – Clean up and format your complex SQL queries for better readability.
- JSON to SQL Converter – Convert JSON data into SQL INSERT statements.
- Guide to Database Normalization – Learn the principles of organizing your database schema effectively.
- Mastering Common Table Expressions (CTEs) – An in-depth guide to using CTEs for more readable and powerful queries.
- Cron Job Generator – Easily create cron expressions for your scheduled tasks.
- Subnet Calculator – A tool for network administrators to plan and calculate IP subnets.