Find nearest latitude/longitude with an SQL query
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Finding the nearest latitude and longitude in SQL usually means calculating distance from a target point to every stored point, then ordering by that distance. The best exact approach depends on your database, but the general strategy is the same whether you use plain SQL math or a spatial extension such as PostGIS.
The Basic Distance Problem
Latitude and longitude are coordinates on a sphere-like surface, not flat x and y values. That means simple Euclidean distance on raw degrees is only an approximation and becomes less accurate over larger areas.
For many databases without full GIS support, the usual fallback is the Haversine formula or a closely related spherical-distance formula.
Plain SQL With Great-Circle Distance
Suppose you have a table called locations:
To find the nearest row to a target latitude and longitude, you can compute the distance inline:
Here 6371 is the approximate Earth radius in kilometers. If you want miles, use about 3959 instead.
This works well for moderate datasets, but it forces the database to compute a distance for many rows unless you reduce the search area first.
Speeding It Up With a Bounding Box
A common optimization is to filter to a rough latitude and longitude window before running the exact distance formula:
The bounding box is an approximation, but it can shrink the candidate set dramatically. After that, the exact formula orders only the nearby rows.
Spatial Databases Are Better When Available
If your database supports geographic types and spatial indexes, use them. In PostGIS, for example, the query becomes both cleaner and faster:
With a proper spatial index, the database can narrow the search efficiently instead of calculating spherical distance for every row in the table.
Schema Design Matters
If nearest-neighbor lookups are important to the application, store the data in a way the database can index effectively. Plain numeric latitude and longitude columns can work, but spatial column types are usually a better long-term design for location-heavy systems.
This matters even more when the dataset grows beyond a few thousand rows. A query that feels instant on a development laptop can become expensive in production if every search scans the whole table.
Common Pitfalls
The biggest mistake is treating latitude and longitude as flat coordinates and using plain Pythagorean distance everywhere. That can be noticeably wrong over larger geographic areas.
Another issue is forgetting that longitude and latitude are ordered differently in some GIS functions. Many APIs expect longitude first and latitude second.
Teams also jump straight to the distance formula without any indexing or bounding-box strategy. That works for tiny tables and then slows down badly as the dataset grows.
Summary
- The general solution is to compute distance from the target point and order by the smallest result.
- Without GIS support, use a spherical-distance formula such as Haversine or an equivalent trigonometric expression.
- Add a bounding-box filter to reduce the number of expensive distance calculations.
- Prefer spatial types and indexes when the database supports them.
- Be careful with coordinate order and with flat-Earth approximations that ignore spherical geometry.
Related reading
- Find nearest value in numpy array
- Find out which features are collinear in a dataset
- Find peak regions in 2D data
- Find records from one table which don't exist in another
- Find nearest points with MySQL from points Table
- Find Oracle JDBC driver in Maven repository
- Find row where values for column is maximal in a pandas DataFrame
- Find rows that have the same value on a column in MySQL

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.