← Back to SQL, page 19

sql-0371 · Hard senior

Users need a 'stores near me' search. How would you support that in SQL?

Store each location's coordinates and use a spatial index. In PostgreSQL, PostGIS geography columns with a GiST index answer nearest-neighbour queries (ORDER BY location <-> point LIMIT 10) and radius filters (ST_DWithin). Without spatial support, filter first by a bounding box on indexed latitude and longitude, then compute exact distances for the remaining rows.

Full answer

PostGIS version:

text
stores(id, name, location geography(Point, 4326));
CREATE INDEX ON stores USING gist (location);
SELECT id, name FROM stores
WHERE ST_DWithin(location, ST_MakePoint(:lon, :lat)::geography, 5000)
ORDER BY location <-> ST_MakePoint(:lon, :lat)::geography LIMIT 10;

Fallback without spatial types:

  1. Compute a bounding box around the user (about 0.045 degrees of latitude per 5 km).
  2. WHERE lat BETWEEN :lat1 AND :lat2 AND lon BETWEEN :lon1 AND :lon2 using an index on (lat, lon).
  3. Calculate the haversine distance for candidates and sort.

SQLite offers an R*Tree module for bounding-box queries. Remember that longitude spacing shrinks towards the poles and the box must handle the 180-degree meridian. The PostGIS statements are shown for illustration and were not run here.

Key points

  • Use spatial types and GiST indexes when available
  • KNN ordering with <-> finds nearest rows
  • Bounding box plus exact distance as a fallback
  • SQLite has R*Tree for boxes
  • Watch the poles and the antimeridian

Common mistakes

  • Computing distance to every row in the table
  • Treating degrees of longitude as fixed distances

Follow-ups

  • How would you combine distance with opening hours?
  • Geometry or geography: which and why?

Tips

  • Describe the two-step fallback