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?
ST_DWithin
can use an index andST_Distance
can notST_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.
We show examples using geography. Note that geometry would use much the same except units are in the spatial reference units.
SELECT roads.road_name, pois.poi_name
FROM roads INNER JOIN pois
ON ST_DWithin(roads.geog, pois.geog, 1609);
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;