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?
ST_DWithin
uses an spatial index (if available).ST_Distance
does notST_DWithin
is more accurate than usingST_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.
We show examples using geography
. Queries using geometry
are similar, but the distance must be 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;