I have a table with about 300k polygons, some are overlapping or adjacent to each other and some are islands of their own. I need to dissolve the overlapping/adjacent ones and also keep the non-overlapping ones. I only need the geometries, no attributes. I can do this with:
create table polygons123_dissolved as
(select (st_dump(st_union(polygons123.wkb_geometry))).geom as geom
from polygons123)
But this is very slow, more than an hour. How can i speed it up?
Explain output:
Result (cost=37684.32..37949.59 rows=1000 width=32)
-> ProjectSet (cost=37684.32..37689.59 rows=1000 width=32)
-> Aggregate (cost=37684.32..37684.33 rows=1 width=32)
-> Seq Scan on polygons123 (cost=0.00..36538.54 rows=229155 width=849)
Filter: ((group_id = 1) AND (type_id = ANY ('{1,2,3}'::integer[])))
ST_Union(geom) WHERE id IN (ids)
where your ids come from the subquery. However, I think ST_Union already uses spatial indexing under the hood, see this article from Paul Ramsey, so it is not clear to me that a subquery will actually be any quicker. Depending on the polygon complexity and how many intersect, 20 minutes for 300k is not necessarily that awful. Perhaps post your EXPLAIN output.