Distance proximity: Use ST_DWithin not Distance
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 + ST_Buffer
.
Use ST_DWithin
instead. Why?
-
ST_DWithin
can use an index andST_Distance
can not -
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 geometry would use much the same except units are in the spatial reference units.
for geography:
Finding closest things within 1609 meters (~1 mile)
1SELECT roads.road_name, pois.poi_name
2 FROM roads INNER JOIN pois
3 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
1SELECT roads.road_name, pois.poi_name
2 FROM roads LEFT JOIN pois
3 ON ST_DWithin(roads.geog, pois.geog, 1609)
4 WHERE pois.gid IS NULL;