You should first create a table from your CSV formatted file, using the COPY
command (if the file is accessible to the PostgreSQL server) or the \copy
command in psql
if the file is not local to the server. See other Q+A on SO for examples if you have any trouble.
Once you have your data in a table, you should convert your longitude
and latitude
columns to the PostGIS geography
type by adding a column to your table of type geography(POINT, 4326)
and then populating that column (here called gps
) with the appropriate values:
UPDATE my_table SET gps = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326);
Add an index on that column to allow for efficient searches:
CREATE INDEX my_table_gps ON my_table USING gist(gps);
You can now find the rows within 5 miles from a given location, e.g. (-72.657, 42.0657)
, as follows:
SELECT *
FROM my_table
WHERE ST_DWithin(gps, ST_SetSRID(ST_MakePoint(-72.657, 42.0657), 4326), 5 * 1609);
Note that ST_DWithin()
on a geography
column will work in meters, so you have to multiply your radius in miles with the 1,609 meters in a mile.