sqlpostgresqlindexingpostgis

How do I query all rows within a 5-mile radius of my coordinates?


Here's a sample of my PostgreSQL in CSV format.

row,latitude,longitude
1,42.082513,-72.621498
2,42.058588,-72.633386
3,42.061118,-72.631541
4,42.06035,-72.634145

I have thousands more rows like these spanning coordinates across the world.

I want to query the table only for coordinates within a certain radius. How do I do this with PostGIS and PostgreSQL?


Solution

  • I did a combo of Erwin's and Patrick's answers.

    -- Add geography column
    ALTER TABLE googleplaces ADD COLUMN gps geography;
    UPDATE googleplaces SET gps = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326);
    CREATE INDEX googleplaces_gps ON googleplaces USING gist(gps);
    
    SELECT *
    FROM my_table
    WHERE ST_DWithin(gps, ST_SetSRID(ST_MakePoint(-72.657, 42.0657), 4326), 5 * 1609);