PostGISMeasurement

ST_3DDistance

What is ST_3DDistance?

ST_3DDistance returns the minimum 3D Cartesian distance between two geometries, using their X, Y, and Z coordinates. It is the 3D counterpart of ST_Distance and is the correct function to use whenever elevation or depth is meaningful.

SQL
ST_3DDistance(geometry g1, geometry g2)float

The result is in the CRS units of the inputs — typically metres when the source data is in a projected CRS such as UTM or local grid. Both inputs must be geometry; there is no geography overload.

When would you use ST_3DDistance?

Use ST_3DDistance in any workflow where elevation matters: computing clearance between overhead power lines and trees, the separation between stacked utility conduits, the distance from an aircraft track to terrain, or the spacing between features in a BIM model. Unlike ST_Distance, it correctly reports that two lines crossing in plan view at different elevations are in fact several metres apart.

SQL
1SELECT a.id, b.id, ST_3DDistance(a.geom, b.geom) AS clearance_m
2FROM power_lines a, tree_canopies b
3WHERE ST_3DDWithin(a.geom, b.geom, 5)
4ORDER BY clearance_m;

FAQs

What happens if one input lacks Z?

Missing Z values are treated as 0. For mixed 2D/3D datasets this produces misleading results — explicitly set or force Z values with ST_Force3D before the call, or ensure your pipeline only stores 3D geometry.

Does ST_3DDistance use a spatial index?

Not directly. For thresholded 3D proximity use ST_3DDWithin, which uses a 3D GiST index (USING GIST (geom gist_geometry_ops_nd)). Without such an index the query will fall back to sequential scans.

What units does it return?

The units of the geometry's CRS — typically metres for projected 3D data such as UTM with elevation in metres. There is no geography version; for spheroidal 3D you would need to compute manually.

Which geometry types are supported?

POINT, LINESTRING, and POLYGON. Triangles, TINs and polyhedral surfaces are supported from PostGIS 2.2+. Collections and curves are not directly supported; decompose them with ST_Dump first.