Calculate distance between two point on earth in PostgreSQL
Come across nice function by Merlin Moncure posted on grokbase.
CREATE OR REPLACE
FUNCTION calculate_distance(lat1 float8, lon1 float8, lat2 float8, lon2 float8)
RETURNS float8 AS
$$
SELECT ACOS(SIN(RADIANS($1)) * SIN(RADIANS($3))
+ COS(RADIANS($1)) * COS(RADIANS($3))
* COS(RADIANS($4) - RADIANS($2))) * 6371;
$$ LANGUAGE 'sql' IMMUTABLE;
More details
Calculating distance between longitude and latitude
Calculate distance, bearing and more