liveBook · Manning

ST_DWithin

As explained in Just Use Postgres!

ST_DWithin is a PostGIS function that tests whether two geometries or geography values are within a specified distance.

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.

How Just Use Postgres! covers it

How deep it goes
Explains distance units, radius-query structure, and index-aware execution, but does not develop the underlying spatial mathematics.
Examples
Demonstrates restaurant and shop searches around named points, supplied coordinates, and transit stations.
What it assumes
Uses geometry values, spatial reference systems, distance units, and spatial indexes as working context.
What you can do after
Apply it via PostGIS to build radius filters and diagnose whether GiST indexes accelerate proximity queries.
How it connects
Connects ST_DWithin to PostGIS geometry, geography, ST_Distance, spatial reference systems, and GiST indexes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.