Haversine Distance To Nearest Depots
Compute great-circle distance from stored lat/lng to a target point with the haversine formula and rank depots nearest first.
Code
-- haversine formula: great-circle distance between two points in kilometers (Earth radius 6371 km)
-- the usual approximation without PostGIS: storing lat/lng as double precision is enough
CREATE TABLE depots (
depot_id int PRIMARY KEY,
depot_name text NOT NULL,
lat double precision NOT NULL,
lng double precision NOT NULL
);
INSERT INTO depots VALUES
(1, 'harbor', 40.7000, -74.0100),
(2, 'midtown', 40.7610, -73.9770),
(3, 'uptown', 40.8100, -73.9500),
(4, 'brooklyn', 40.6800, -73.9400);
-- target point: Times Square (40.7580, -73.9855)
-- distance = 2 * R * asin(sqrt(sin²(Δφ/2) + cosφ1·cosφ2·sin²(Δλ/2)))
-- rank depots nearest first: ORDER BY ascending + LIMIT
SELECT
depot_id,
depot_name,
ROUND((2.0 * 6371.0 * ASIN(SQRT(
POWER(SIN(RADIANS(40.7580 - lat) / 2), 2)
+ COS(RADIANS(lat)) * COS(RADIANS(40.7580))
* POWER(SIN(RADIANS(-73.9855 - lng) / 2), 2)
)))::numeric, 1) AS distance_km
FROM depots
ORDER BY distance_km
LIMIT 3;How it works
What runs here is SELECT / INSERT / CREATE — depots are the objects involved.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Run the statement against the depots table; the LIMIT keeps the probe cheap while you tune the predicates.
Core lines
SELECT
depot_id,
depot_name,
ROUND((2.0 * 6371.0 * ASIN(SQRT(
POWER(SIN(RADIANS(40.7580 - lat) / 2), 2)
+ COS(RADIANS(lat)) * COS(RADIANS(40.7580))
* POWER(SIN(RADIANS(-73.9855 - lng) / 2), 2)
)))::numeric, 1) AS distance_km
FROM depots
ORDER BY distance_km
LIMIT 3;
INSERT INTO depots VALUES
(1, 'harbor', 40.7000, -74.0100),
(2, 'midtown', 40.7610, -73.9770),
(3, 'uptown', 40.8100, -73.9500),
(4, 'brooklyn', 40.6800, -73.9400);
CREATE TABLE depots (
depot_id int PRIMARY KEY,
depot_name text NOT NULL,
lat double precision NOT NULL,
lng double precision NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.
FAQ
- What are the relations in play here?
- `depots`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.