ST_UnaryUnion
What is ST_UnaryUnion?
ST_UnaryUnion dissolves a single geometry with itself, merging overlapping parts and noding self-intersections. Unlike the aggregate ST_Union, which takes many rows, ST_UnaryUnion works on one multi-geometry or collection and returns a cleaned union.
1ST_UnaryUnion(geometry geom) → geometry
2ST_UnaryUnion(geometry geom, float gridSize) → geometryThe optional gridSize (PostGIS 3.1+) snaps inputs to a fixed precision grid for robustness.
When would you use ST_UnaryUnion?
Use ST_UnaryUnion to clean up a single collection geometry: dissolving overlapping polygons inside a MULTIPOLYGON, noding self-intersecting MULTILINESTRINGs, or combining the output of ST_Collect into a valid dissolved geometry. It is the per-row equivalent of calling ST_Union as an aggregate — cheaper when your data is already collected into one geometry per row.
1-- Dissolve internal overlaps in each row's multi-polygon
2UPDATE layers
3SET geom = ST_UnaryUnion(geom)
4WHERE GeometryType(geom) = 'MULTIPOLYGON';FAQs
How does it differ from ST_Union?
ST_Union is an aggregate across rows — it unions the geometries of many rows into one. ST_UnaryUnion is a per-row function that dissolves internal overlaps inside a single collection geometry.
Does it fix invalid geometries?
It noding self-intersections and merges overlapping parts, which often produces a valid result from an invalid MULTIPOLYGON. For general validation use ST_MakeValid; for a specific "merge into one clean geometry", ST_UnaryUnion is more predictable.
When should I use ST_UnaryUnion vs ST_Union vs ST_Collect?
ST_Collect just groups geometries into a collection — fast, but does not merge overlaps. ST_UnaryUnion merges overlaps within one geometry. ST_Union as an aggregate merges across rows. A common idiom is ST_UnaryUnion(ST_Collect(geom)) in a window function, which is often faster than aggregate ST_Union on large groups.
What about Z and M?
The operation is 2D. Z and M may be dropped or made inconsistent by the overlay. If you need to preserve Z, handle the union in 3D-aware tooling (SFCGAL) or re-attach Z from the original geometry.