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

Use ST_DWithin not ST_Distance for radius queries

If you have a problem that involves finding the things within X distance of other things or finding what things “have nothing within X distance” do not use ST_Distance for filtering and also do not try to use ST_Intersects with ST_Buffer.

Use ST_DWithin instead. Why?

  1. ST_DWithin can use an index and ST_Distance can not
  2. ST_Buffer is just an approximation of a buffer and not an exact buffer

Also note that ST_DWithin is supported for both geometry and geography.

Examples

We show examples using geography. Note that geometry would use much the same except units are in the spatial reference units.

Finding closest 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;