
PostGIS Spatial Indexing: Why Your Queries Are Doing Sequential Scans
The One PostGIS Function Swap That Makes Spatial Queries 1000x Faster I have seen this exact pattern break production at three different companies. A location-based feature ships, it works great in staging, and then it hits production with millions of rows and every "find nearby" query takes seconds instead of milliseconds. The cause is always the same: ST_Distance in a WHERE clause. The Function That Looks Right But Isn't This query is logically correct. It finds all points of interest within roughly 1 km of a location: SELECT name , ST_Distance ( geom , ST_SetSRID ( ST_MakePoint ( - 73 . 9857 , 40 . 7484 ), 4326 )) AS dist FROM points_of_interest WHERE ST_Distance ( geom , ST_SetSRID ( ST_MakePoint ( - 73 . 9857 , 40 . 7484 ), 4326 )) < 0 . 01 ; It returns the right results. It also forces PostgreSQL to compute the exact distance between the query point and every single geometry in the table. On 5 million rows, that is 5 million distance calculations before any filtering happens. The
Continue reading on Dev.to
Opens in a new tab




