Distance & Buffer Queries

~20 min read

Distance & Buffer Queries

Spatial queries let you ask geographic questions of your data.

Find Distance Between Cities

sql
SELECT
    a.name AS city_a,
    b.name AS city_b,
    ST_Distance(a.geom::geography, b.geom::geography) / 1000 AS distance_km
FROM cities a, cities b
WHERE a.name = 'London' AND b.name != 'London';

Buffer Around a Point

Create a 100km buffer around London:

sql
SELECT ST_Buffer(geom::geography, 100000)::geometry AS buffer_geom
FROM cities
WHERE name = 'London';

Find Cities Within a Radius

sql
SELECT name, population
FROM cities
WHERE ST_DWithin(
    geom::geography,
    (SELECT geom::geography FROM cities WHERE name = 'London'),
    500000  -- 500km
);

These are the building blocks of spatial analysis in PostGIS!

← Previous