PostGISMeasurement

ST_ShortestLine

What is ST_ShortestLine?

ST_ShortestLine returns a two-point LINESTRING connecting the closest point on geometry g1 to the closest point on geometry g2. Its length equals ST_Distance(g1, g2); if the two geometries intersect, it is a degenerate zero-length line at an intersection point.

SQL
1ST_ShortestLine(geometry g1, geometry g2)geometry
2ST_ShortestLine(geography g1, geography g2, boolean use_spheroid = true) → geography

A geography overload was added in PostGIS 3.4 and returns a two-point geography following the shortest great-circle / spheroidal path.

When would you use ST_ShortestLine?

Use ST_ShortestLine whenever you need the visible "tether" between two features — drawing connectors from addresses to their nearest road, depicting the minimum-clearance span between assets, or placing labels at the closest point between a feature and a reference. It is also a clean way to get both endpoints from a closest-pair calculation in one call.

SQL
1-- Connector lines from each GPS fix to the nearest road centreline
2SELECT ST_ShortestLine(gps.geom, road.geom) AS connector
3FROM gps_fixes gps
4JOIN LATERAL (
5  SELECT geom
6  FROM roads
7  ORDER BY roads.geom <-> gps.geom
8  LIMIT 1
9) AS road ON TRUE;

FAQs

What is the relationship with ST_Distance?

ST_Length(ST_ShortestLine(g1, g2)) = ST_Distance(g1, g2). ST_ShortestLine gives you the geometry; ST_Distance gives you the scalar.

Is it symmetric?

Yes in length. The LINESTRING direction (start on g1, end on g2) follows the argument order.

Is there a 3D version?

Yes — ST_3DShortestLine uses Z coordinates to produce the 3D closest-pair line.

Does the geography overload follow a great circle?

Yes. On geography, the returned two-point line represents the spheroidal (or spherical, with use_spheroid = false) shortest path; note that it is stored as two endpoints, not a densified arc — densify with ST_Segmentize before rendering if you need a visible curve.