ST_DWithin tests whether two PostGIS geometry or geography values lie within a specified distance. For geometry values, the distance uses the units defined by their spatial reference system. section 10.5.1 section 10.7
Use ST_DWithin to limit candidates before measuring and sorting them:
- Join a reference point to nearby features with ST_DWithin(..., 500), which keeps rows inside a 500-unit radius. section 10.5.1
- Pair the predicate with ST_Distance to calculate, display, and order the surviving results by nearest distance. section 10.5.1
- Prefer the index-aware predicate over ST_Distance(...) <= 500 when a GiST spatial index can accelerate the search. section 10.6.2 section 10.7
Find restaurants within 500 meters
WITH roost_hotel AS ( SELECT way FROM florida.planet_osm_point WHERE name = 'Roost Apartment Hotel' AND tourism = 'hotel' ) SELECT p.name, p.amenity, round(ST_Distance(h.way, p.way)) AS distance_meters FROM roost_hotel AS h JOIN florida.planet_osm_point AS p ON ST_DWithin(h.way, p.way, 500) WHERE p.amenity = 'restaurant' ORDER BY distance_meters LIMIT 5; The query returns five restaurants, including Wagamama at 68 meters and Boulon Brasserie at 132 meters.
Use the spatial index
A Brickell City Centre query uses ST_DWithin to find shops within 500 meters and returns the 10 nearest matches. Its execution plan shows a bitmap heap scan for the spatial candidates, while replacing the predicate with ST_Distance(...) <= 500 removes 18,640 rows through a join filter and takes substantially longer.
