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:
- Compute a bounding box around the user (about 0.045 degrees of latitude per 5 km).
WHERE lat BETWEEN :lat1 AND :lat2 AND lon BETWEEN :lon1 AND :lon2using an index on (lat, lon).- 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