SQL
geolocation
latitude and longitude
location clustering
spatial data

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.

Practice ML system design

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.

sql
1SELECT
2    FLOOR(latitude * 100) / 100.0 AS lat_bucket,
3    FLOOR(longitude * 100) / 100.0 AS lon_bucket,
4    COUNT(*) AS point_count
5FROM locations
6GROUP BY
7    FLOOR(latitude * 100) / 100.0,
8    FLOOR(longitude * 100) / 100.0
9ORDER BY point_count DESC;

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.

sql
1CREATE TABLE locations (
2    id SERIAL PRIMARY KEY,
3    name TEXT NOT NULL,
4    geom GEOGRAPHY(POINT, 4326) NOT NULL
5);
6
7INSERT INTO locations (name, geom)
8VALUES
9    ('Office', ST_SetSRID(ST_MakePoint(-79.3832, 43.6532), 4326)::geography),
10    ('Cafe', ST_SetSRID(ST_MakePoint(-79.3818, 43.6525), 4326)::geography);

With that representation, finding nearby pairs becomes straightforward:

sql
1SELECT a.id AS location_a, b.id AS location_b
2FROM locations a
3JOIN locations b
4  ON a.id < b.id
5 AND ST_DWithin(a.geom, b.geom, 500);

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:

sql
1SELECT
2    id,
3    name,
4    ST_ClusterDBSCAN(geom::geometry, eps := 0.01, minpoints := 2) OVER () AS cluster_id
5FROM locations;

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:

sql
CREATE INDEX locations_geom_idx
ON locations
USING GIST (geom);

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_ClusterDBSCAN when available.
  • Spatial indexes are essential once the dataset is large enough to matter.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track 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.

Practice ML system design

All Rights Reserved.