PostGIS-focused SQL tips, tricks and gotchas. Use when in need of dealing with geospatial data in Postgres.
-- in front of it.st_segmentize -> ST_Segmentize).geom; geography column geog.including on same index for faster lookup.select postgis_full_version(); to see if all upgrades happened successfully.sum(case when A then 1 else 0 end) is just count() filter (where A)row_number() ... = 1 can likely be redone as order by + limit 1 (possibly with distinct on or lateral)exists(select 1 from ...) is just exists(select from ...)tags ->> 'key' = 'value' is just tags @> '{"key": "value"} - works faster for indexesorder bygeometry(multilinestring, 4326)) - use plain geometry or geography instead. This removes clutter of ST_Multi and errors via ST_SetSRID.ST_UnaryUnion(ST_Collect(geom)) is just ST_Union(geom)ST_Buffer(geom, 0) should be ST_MakeValid(geom)select min(ST_Distance(..)) should be select ST_Distance() ... order by a <-> b limit 1 to enable knn gistorder by ST_Distance(c.geog, t.geog) should be order by c.geog <-> t.geogST_UnaryUnion is a sign you're doing something wrongST_MakeValid is a sign you're doing something wrong on the previous stepST_SetSRID: check the actual projection of input data, check if it can be set correctly during input (ST_GeomFromGeoJSON, EWKT-style SRID=4326;POINT(..., EWKB allow that). Check if ST_Transform is needed instead.ST_Intersects to other topology predicatesST_Simplify(geom, 0)ST_ClusterKMeans with k=2 and max_radius set to your distance.ST_AsEWKB for binary representation instead of ST_AsWKB to keep SRID.ST_Hexagon / ST_HexagonGrid use h3 extension.ST_QuantizeCoordinates if precision is known.