PostGIS
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Use ST_DWithin for radius queries

For queries that involve finding “things within distance X of other things” or “what things have nothing within distance X”, use ST_DWithin for filtering. Do not use ST_Distance or ST_Intersects with ST_Buffer.

Why?

  1. ST_DWithin uses an spatial index (if available). ST_Distance does not
  2. ST_DWithin is more accurate than using ST_Buffer, which is only approximation of a true buffer outline. It is also amost always faster.

Note that ST_DWithin is supported for both geometry and geography types.

Examples

We show examples using geography. Queries using geometry are similar, but the distance must be in the spatial reference units.

Finding things within 1609 meters (~1 mile)

SELECT roads.road_name, pois.poi_name
 FROM roads INNER JOIN pois
   ON ST_DWithin(roads.geog, pois.geog, 1609);

Finding roads with nothing of interest within 1 mile

We are using the fact that a LEFT JOIN returns NULL in the left table when no match is found.

SELECT roads.road_name, pois.poi_name
 FROM roads LEFT JOIN pois
   ON ST_DWithin(roads.geog, pois.geog, 1609)
   WHERE pois.gid IS NULL;