0PricingLogin
SQL Academy · Lesson

Distance and Nearest Neighbors

Find what's close by.

What Is Spatial Distance?

In geospatial databases, distance is the measured separation between two geographic locations. PostGIS provides powerful functions to compute distances between points, lines, polygons, and other geometry types.

Understanding distance queries lets you answer questions like: What is the nearest restaurant to me? or Which customers are within 5 km of our warehouse?

The ST_Distance Function

ST_Distance(geom_a, geom_b) returns the minimum distance between two geometry objects. By default, when using plain geometry types, the result is in the same units as the coordinate reference system (usually degrees for EPSG:4326).

To get meaningful results in meters, you should use geography types or reproject your data.

SELECT ST_Distance(
  ST_MakePoint(28.9784, 41.0082)::geography,
  ST_MakePoint(29.0100, 41.0200)::geography
) AS distance_meters;

All lessons in this course

  1. Spatial Data Types
  2. Distance and Nearest Neighbors
  3. Spatial Joins and Containment
  4. Spatial Indexes (GiST)
← Back to SQL Academy