ST_Distance calculates the minimum two-dimensional Cartesian distance between two geometries. The result uses the units defined by the geometries’ spatial reference system. section 10.5.1
Find nearby restaurants
Combine ST_Distance with ST_DWithin to filter and rank restaurants around a hotel: WITH roost_hotel AS ( SELECT way FROM florida.planet_osm_point WHERE name = 'Roost Apartment Hotel' AND tourism = 'hotel' ) SELECT p.name, round(ST_Distance(h.way, p.way)) AS distance_meters, round(ST_Distance(h.way, p.way) * 3.28) AS distance_feet 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 Wagamama at 68 meters, followed by Boulon Brasserie at 132 meters. section 10.5.1
Use ST_Distance to calculate exact distances after filtering candidates. It is not index-aware; using it directly in a distance predicate can trigger a parallel full-table scan, whereas ST_DWithin can use a GiST index for initial filtering. section 10.6.2
Listing 10.14 Finding the closest restaurants
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, round(ST_Distance(h.way,p.way) * 3.28) as distance_feet 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;
Runnable SQL and sample output demonstrate filtering within 500 meters, calculating distances in meters and feet, and ordering the nearest results. section 10.5.1
