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.

SqlData Fetching

Code

snippet
-- 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

FAQ

What are the relations in play here?
`depots`.