How to group nearby latitude and longitude locations stored in SQL
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
Grouping nearby latitude and longitude values is a spatial problem, not an ordinary GROUP BY problem. Before you write SQL, you need to decide what "nearby" means for your application: rough map buckets, points within a fixed radius, or true clusters built from spatial relationships.
Start by Choosing the Kind of Grouping You Need
There are three common meanings of "group nearby locations":
- place points into coarse geographic cells
- find points that are within a chosen distance of one another
- compute actual spatial clusters
Those are related, but they are not interchangeable. A dashboard heatmap may only need coarse buckets. A delivery app might need all locations within 500 meters. An analytics system might need density-based clusters rather than arbitrary rectangular boxes.
If you skip this definition, it is easy to build a query that is technically correct and still wrong for the product.
Grid Bucketing Works in Plain SQL
If an approximate answer is enough, bucket the coordinates into cells by rounding or flooring them. This is simple, portable SQL and often good enough for summary counts.
This groups points into cells of roughly 0.01 degrees. It is fast and easy to explain, but it is only an approximation. Degrees of longitude do not represent the same physical distance everywhere on Earth, and bucket edges can split two very close points into different groups.
So this method is best when you want map aggregation, not precise proximity logic.
Use Spatial Types for Real Distance Queries
If you actually mean "within N meters," use a spatial database feature set. In PostgreSQL with PostGIS, store points as geography or geometry instead of raw numeric columns alone.
With that representation, finding nearby pairs becomes straightforward:
This query returns pairs of points within 500 meters of each other. It is already much closer to the natural meaning of "nearby" than latitude rounding.
Use Clustering When You Need Group IDs
Pairwise distance queries tell you which points are neighbors, but they do not automatically assign cluster identifiers. If you want output such as "these ten points belong to cluster 3," use a spatial clustering feature when your database provides one.
PostGIS offers DBSCAN-style clustering:
This is often the best answer when your product really needs cluster membership rather than fixed-size map cells. The eps setting controls neighborhood size, and minpoints controls how dense a group must be before it becomes a cluster.
If your database does not provide clustering functions, you can still build clusters with recursive queries or application-side graph logic, but at that point a spatial extension is usually worth it.
Indexing and Scale Matter
Distance joins are expensive without spatial indexes. In PostGIS, create a GiST index so proximity predicates do not degenerate into full scans:
If you only store raw latitude and longitude numbers and compute distance with custom formulas in every join, the query cost grows quickly as the table grows. Plain SQL formulas can work for small datasets, but they are usually the wrong long-term foundation for production geospatial grouping.
If you have no spatial extension at all, you can still approximate great-circle distance with the Haversine formula, but that should be treated as a fallback rather than the ideal design.
Common Pitfalls
The most common mistake is using GROUP BY latitude, longitude and expecting it to find nearby points. That only groups exact coordinate matches.
Another mistake is using rounded degree buckets as though they were true distance-based groups. They are easy to compute, but they are only approximations and become especially misleading across larger regions.
People also underestimate the cost of pairwise distance joins. Without spatial indexes, a "nearby" query can become unacceptably slow as the data grows.
Finally, make sure your definition of nearby matches the product requirement. Grid aggregation, radius matching, and clustering each answer a different business question.
Summary
- Nearby-location grouping is a spatial problem, not a plain equality grouping problem.
- Grid bucketing is simple and useful for approximate map aggregation.
- For true distance checks, use spatial types and predicates such as
ST_DWithin. - For real cluster membership, use a clustering function such as
ST_ClusterDBSCANwhen available. - Spatial indexes are essential once the dataset is large enough to matter.
Related reading
- How to handle a situation of feature scaling in machine learning model deployment when you have only one testing instance?
- How to handle categorical variables in sklearn GradientBoostingClassifier?
- How to handle date variable in machine learning data pre-processing
- How to handle large amouts of data in tensorflow?
- How to handle consensus in a decentralized event sourced database?
- How to handle data migrations in distributed microservice databases
- How to handle large amouts of data in tensorflow?
- How to handle log0 when using cross entropy

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.