I am looking for a method, using PostGIS, of reconstituting a set of polygons from tens of thousands of smaller polygon 'pieces'.

This is a simplified example, with the pieces shaded:Polygon pieces

Unfortunately, the pieces do not have a common ID or other attribute of the larger polygons that would allow me to group them. In some cases, I have the grid that was used to cut the pieces, but in other cases I do not.

The only approach I've been able to devise -- and I haven't been able to make it work yet -- is to use ST_BuildArea on pairs of intersecting pieces in an iterative process as follows (renaming 'composite' to 'pieces' between iterations):

SELECT p1.id,ST_BuildArea(ST_Collect(p1.the_geom,p2.the_geom)) AS the_geom
INTO composite
FROM pieces p1 LEFT OUTER JOIN pieces p2
    ON (ST_DWithin(p1.the_geom,p2.the_geom,1))
WHERE ST_Intersects(p1.the_geom,p2.the_geom) AND
p1.id < p2.id;

This generates larger and larger composite pieces, but many of them (nearly 1,300 after three iterations on the example), and they come increasingly to overlap. It seems to me that to go much further I'd need a means of paring down the results each iteration. (I'm also getting side location conflicts on the fourth iteration, but that may be a separate problem.)

  • If two polygons touch, does that mean they need to be dissolved? And finally you will have just non touching polygons? Mar 19, 2013 at 11:18
  • 3
    Have you looked at: gis.stackexchange.com/questions/24634 , especially the first answer? Mar 19, 2013 at 11:28
  • Devdatta -- cheers. 1) Yes, touching polygons should be dissolved so that ultimately no polygons touch.
    – saint_utz
    Mar 19, 2013 at 12:47
  • 2) I had not seen that post, and it would present a fairly straightforward solution. I guess the question would become how many polygons I could union at a time w/o my system falling over (I may need to do millions spread over a tens of thousands of kilometres). Perhaps way forward would be multi-step: first union/dump within tiles of a much larger-scale grid; then select any polygons that intersect borders of the grid into new table; then union/dump those; then combine all 'freestanding' polygons.
    – saint_utz
    Mar 19, 2013 at 12:52

1 Answer 1


The simplest and fastest solution I found for this problem is

SELECT ST_UnaryUnion(unnest(ST_ClusterIntersecting(geom))) FROM pieces;

Dissolving a set of 165,000 polygons took 38 seconds in my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.