PostGISMeasurement

ST_Distance

What is ST_Distance?

ST_Distance returns the minimum 2D Cartesian distance between two geometries, or the minimum spheroidal distance between two geographies. It is the canonical proximity measurement in PostGIS and returns 0 for any pair of geometries that intersect.

SQL
1ST_Distance(geometry g1, geometry g2)float
2ST_Distance(geography geog1, geography geog2, boolean use_spheroid = true)float

For geometry input, distance is expressed in the CRS units of the inputs — degrees for EPSG:4326, metres for UTM and other projected CRSs. For geography input, distance is always in metres on the WGS84 spheroid (set use_spheroid = false for the faster sphere approximation).

When would you use ST_Distance?

Use ST_Distance any time you need an exact proximity figure: computing the distance from a customer address to the nearest store, ranking hospitals by distance to a patient's address, or sorting search results by how far a point of interest is from the map centre. It is also used inside ORDER BY clauses for nearest-neighbour queries, though for index-accelerated K-NN you should use the <-> operator. For proximity filtering, always prefer ST_DWithin — it uses a spatial index while ST_Distance alone does not.

SQL
1-- All hospitals within 5 km of a school, sorted by distance
2SELECT h.name, ST_Distance(s.geom::geography, h.geom::geography) AS metres
3FROM schools s, hospitals h
4WHERE s.id = 7
5  AND ST_DWithin(s.geom::geography, h.geom::geography, 5000)
6ORDER BY metres;

FAQs

What units does ST_Distance return?

For geometry, the result is in the SRID's units (degrees for lat/lon, metres for most projected CRSs). For geography, the result is always in metres on the WGS84 spheroid. Cast lat/lon columns to geography with ::geography when you need real-world distances.

Does ST_Distance use a spatial index?

ST_Distance alone does not use a GiST index — each pair is computed in full. For thresholded queries ("within X metres") use ST_DWithin, which uses the index. For ordered nearest-neighbour queries use the <-> operator with ORDER BY geom <-> 'POINT(...)' and a LIMIT — this is index-accelerated on GiST.

Is there a 3D version?

Yes — ST_3DDistance uses Z coordinates and returns the full 3D Euclidean distance. ST_Distance always projects to 2D and ignores Z.

What is the performance difference between geometry and geography?

geometry distance is a fast planar computation. geography distance runs spheroidal calculations and is slower — typically several times slower per pair. Pass use_spheroid = false to drop to the spherical approximation (about 0.3% error, much faster), or reproject to a local projected CRS for bulk work.