Arman Pouyaei Start a conversation
Lesson 22  ·  Nov 2, 2026
Data Engineering Fundamentals

Near me, in SQL: spatial filters with ST_DWithin

Phase 2 starts here — and it starts with the question plain SQL cannot answer: what is near this point? A WHERE filter can match a region name or a latitude range, but it cannot measure distance. Spatial SQL adds a geometry column to the table and a family of ST_ functions that understand location. Today: one function, ST_DWithin — the spatial version of a WHERE filter.

The code

SELECT station_id, name
FROM weather_stations
WHERE ST_DWithin(
  geom,
  ST_SetSRID(ST_MakePoint(-74.0060, 40.7128), 4326),
  50000
);

geom is the station's location, stored as a geometry (a point) instead of two separate lat/lon numbers. ST_MakePoint(-74.0060, 40.7128) builds the reference point — longitude first, latitude second, which is the classic gotcha — and ST_SetSRID(..., 4326) says the coordinates are GPS lat/lon (SRID 4326 is the standard code for that). ST_DWithin(geom, point, 50000) is then true for every station within 50,000 metres — 50 km — of that New York City point. Same shape as every WHERE you already know; the predicate just happens to be spatial.

In practice

This is the workhorse query of geospatial pipelines: which sensors sit within the storm's footprint, which stations are near a flood gauge, which assets fall inside a 10 km buffer around a site. A data engineer writes it as a filter step — in a view, in an ETL query, or as the WHERE clause that feeds a downstream join. And like the indexes from Lesson 11, it has a performance story: a spatial (GiST) index on geom lets the database skip straight to nearby rows instead of measuring the distance to every station in the table.

Python bridge: pandas has no built-in "nearby" filter — you would compute a haversine distance row by row and then filter. Spatial SQL pushes that whole step into the database as one predicate, which is exactly why teams keep geometry in the warehouse instead of in flat files.

Further reading

Your First Steps With the Geography Data Type — LearnSQL (a beginner-friendly PostGIS intro: the geography type, how points are stored, and the first distance queries)

Try it

Practice question: using the same weather_stations table, write a query that returns the station_id and name of every station within 10 km of Times Square, at longitude -73.9857, latitude 40.7484.

Show answer
SELECT station_id, name
FROM weather_stations
WHERE ST_DWithin(
  geom,
  ST_SetSRID(ST_MakePoint(-73.9857, 40.7484), 4326),
  10000
);

Result: one row per station whose point lies within 10,000 metres of Times Square — the Manhattan stations in the table, in other words. Stations in Princeton or Boston are further than 10 km away, so they drop out. Only two things changed from the example: the reference point and the distance, from 50000 down to 10000.

← All posts