Search code examples
postgresqlpostgis

How to select all the geographic POINTS within a Rectangle in Postgis?


I have a table USERS, this table has a column called coordinates of type geography(point, 4326)

I would like to construct a query to select all the coordinates within a rectangle.

These are the coordinates of each corner of the rectangle:

topRight: lat: 40.136910949186415 lng: -104.603574437409
topLeft: lat: 40.136910949186415 lng: -105.48495964571721
bottomRight: lat: 39.728134609342135 lng: -104.603574437409
bottomLeft: lat: 39.728134609342135 lng: -105.48495964571721

Solution

  • SELECT *
      FROM USERS
     WHERE ST_Intersects
         ( coordinates
         , ST_MakeEnvelope ( -105.48495964571721 -- xmin (min lng)
                           , 39.728134609342135 -- ymin (min lat)
                           , -104.603574437409 -- xmax (max lng)
                           , 40.136910949186415 -- ymax (max lat)
                           , 4326 -- projection epsg-code
                           )::geography('POLYGON') 
         )