ST_DWithin
What is ST_DWithin?
ST_DWithin returns true if two geometries (or geographies) are within a given distance of each other. It is the index-accelerated answer to "is feature A within X units of feature B?" and the function to reach for in any proximity WHERE or JOIN clause.
1ST_DWithin(geometry g1, geometry g2, float distance) → boolean
2ST_DWithin(geography gg1, geography gg2, float distance_meters, boolean use_spheroid = true) → booleanFor geometry, distance is in the CRS units — degrees for EPSG:4326 (rarely what you want), metres for most projected CRSs. For geography, distance is always in metres on the WGS84 spheroid.
When would you use ST_DWithin?
Use ST_DWithin any time you need a thresholded proximity check on indexed geometry: finding all hospitals within 5 km of each school, all cell towers within 500 m of a new antenna, or all addresses within 100 m of a transit stop. Unlike ST_Distance < X, which requires full distance computation per pair, ST_DWithin uses the GiST index to prune candidates and is orders of magnitude faster on large datasets.
1-- All hospitals within 5 km of each school, using geography for metre accuracy
2SELECT s.id AS school, h.id AS hospital
3FROM schools s
4JOIN hospitals h
5 ON ST_DWithin(s.geom::geography, h.geom::geography, 5000);FAQs
Why is ST_DWithin faster than ST_Distance < d?
ST_DWithin expands each candidate's bounding box by the distance threshold and probes a GiST index, so it only exact-tests pairs that could plausibly satisfy the threshold. ST_Distance < d has no index support and must compute distance for every pair.
What units does the distance parameter use?
For geometry, the units of the CRS — usually degrees for lat/lon, metres for projected. For geography, always metres. For metre-based proximity on lon/lat data, cast to geography or first reproject.
Do I need a spatial index?
Yes, for ST_DWithin to live up to its performance reputation the input must have a GiST index on the geometry/geography column. Without one it falls back to a sequential scan and is no faster than ST_Distance < d.
Is there a 3D version?
Yes — ST_3DDWithin uses Z coordinates. Pair it with a 3D GiST index (USING GIST (geom gist_geometry_ops_nd)) for index-accelerated 3D proximity queries.