Ive spent enough time goofing around with location-finder software that its worth writing up how to do it.   Of course, finding distances on the surface of the earth means using Great Circle distances, worked out with the Haversine formula, also called the Spherical Cosine Law formula.Lets say we only care about points in the zip code table that are within 50 km of the (latpoint, longpoint).I have the following code:SELECT zip, latitude, longitude, distanceFROM (  SELECT z.zip,         z.latitude, z.longitude,         p.radius,         p.distance_unit            * DEGREES(ACOS(COS(RADIANS(p.latpoint))            * COS(RADIANS(z.latitude))            * COS(RADIANS(p.longpoint - z.longitude))            + SIN(RADIANS(p.latpoint))            * SIN(RADIANS(z.latitude)))) AS distance   FROM zip AS z   JOIN (   /* these are the query parameters */      SELECT  42.81 AS latpoint, -70.81 AS longpoint,              50.0  AS radius,  111.045 AS distance_unit        ) AS p ON 1=1   WHERE z.latitude      BETWEEN p.latpoint  - (p.radius / p.distance_unit)          AND p.latpoint  + (p.radius / p.distance_unit)   AND z.longitude      BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))          AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))      ) AS dWHERE distance <= radiusIs there any way to improve a performance of this query?
Compute haversine distance between point and table of points
performance;sql;postgresql;geospatial