ST_CollectionExtract
What is ST_CollectionExtract?
ST_CollectionExtract takes a GeometryCollection and returns a homogeneous Multi-geometry containing only components of the requested dimension — points, lines, or polygons. It is the canonical way to pull a typed feature class out of a mixed collection.
1ST_CollectionExtract(geometry collection) → geometry
2ST_CollectionExtract(geometry collection, integer type) → geometrytype is 1 for points, 2 for lines, and 3 for polygons. When called without a type, PostGIS picks the highest-dimension components present. If the collection contains no geometry of the requested type, an empty MULTI* of that type is returned.
When would you use ST_CollectionExtract?
Use ST_CollectionExtract after overlay operations — ST_Intersection, ST_Difference, or ST_SymDifference — where the result can legitimately be a GeometryCollection mixing points, lines, and polygons even when only polygons are wanted. Pass type = 3 to keep the polygonal output and discard stray boundary artifacts that appear as points or lines.
It is also handy when loading heterogeneous feature data into a table whose geometry column has a type constraint such as MULTIPOLYGON, letting you coerce mixed input while dropping noise from topology errors.
FAQs
What does type = 1, 2, or 3 mean?
These match OGC dimension codes — 1 extracts points (0-dimensional), 2 extracts lines (1-dimensional), and 3 extracts polygons (2-dimensional). The result is always a MULTI* geometry of the corresponding type.
Why do I still get a GeometryCollection back?
You are probably calling the single-argument form, which preserves the collection when multiple dimensions are present. Pass an explicit type argument to force a homogeneous result.
What is the difference between ST_CollectionExtract and ST_CollectionHomogenize?
ST_CollectionExtract filters to one geometry type and returns a Multi-geometry. ST_CollectionHomogenize simplifies a collection by returning the simplest possible equivalent geometry — e.g. a single-element collection becomes a bare geometry — but never drops components.
Does ST_CollectionExtract handle nested collections?
Yes. PostGIS recurses into nested collections, so components at any depth that match the requested type are included in the output.