postgis-dwithin
ST_DWithin (Distance / Proximity Queries)
Use this skill when you need to find features within a given distance of another geometry:
- “points within X meters of a line”
- proximity searches around a point
- replacing expensive buffer + intersects patterns
Core rules
ST_DWithinis faster thanST_Distance < x- Units depend on input type:
geometry→ SRID unitsgeography→ meters
- Geometries must be in the same SRID
- Prefer
ST_DWithinover buffering when you only need a boolean test
Canonical patterns
Geometry (projected CRS, SRID units)
Use when your data is stored in a projected SRID (feet/meters).
SELECT *
FROM points p
JOIN lines l
ON ST_DWithin(p.geom, l.geom, 5);
Distance 5 is in the SRID’s units.
Geography (meters, easiest default)
Use when geometry is stored in EPSG:4326 and you want meters.
SELECT *
FROM points p
JOIN lines l
ON ST_DWithin(
p.geom::geography,
l.geom::geography,
5
);
Distance 5 is meters.
Transform once (projected math, better for large jobs)
When using a client/project SRID:
SELECT *
FROM points p
JOIN lines l
ON ST_DWithin(
ST_Transform(p.geom, client_srid),
ST_Transform(l.geom, client_srid),
5
);
Transforming both sides is acceptable here because ST_DWithin can still use indexes in many cases, but prefer transforming the smaller side if possible.
Point near line (common validation pattern)
SELECT p.*
FROM points p
JOIN lines l
ON ST_DWithin(
p.geom::geography,
l.geom::geography,
5
);
Use this instead of buffering lines unless you need the actual corridor geometry.
Index requirements
Ensure GiST indexes exist:
CREATE INDEX IF NOT EXISTS points_geom_gix ON points USING gist (geom);
CREATE INDEX IF NOT EXISTS lines_geom_gix ON lines USING gist (geom);
ST_DWithin can leverage spatial indexes when used correctly.
Common mistakes
- Using
ST_Distance(...) < xinstead ofST_DWithin - Forgetting geometry vs geography unit differences
- Mixing SRIDs without transforming
- Buffering geometries just to test proximity
Summary
- Prefer
ST_DWithinfor distance tests - Use
geographyfor meters when in 4326 - Use projected SRIDs for heavy planar work
- Index geometry columns
More from mmbmf1/geospatial-skills
geojson-postgis
Serialize PostGIS geometry rows into a GeoJSON FeatureCollection for map display (4326, Feature + properties).
20geojson-points
Convert JSON rows with latitude/longitude fields into a GeoJSON FeatureCollection using raw PostGIS SQL.
16geojson-wkt
Convert JSON rows with WKT geometry strings into a GeoJSON FeatureCollection using raw PostGIS SQL.
13postgis-distance
Compute numeric distances safely with ST_Distance (geometry vs geography units) and pair with ST_DWithin for performance.
9postgis-nearest
Find nearest features efficiently using PostGIS KNN (<->) and distance ordering (with SRID/unit guidance).
7postgis-extract-xy
Extract longitude and latitude from PostGIS geometries using ST_X and ST_Y safely.
7