PostGISGeometry Accessors

ST_GeometryN

What is ST_GeometryN?

ST_GeometryN is a PostGIS function that returns the Nth component of a multi-geometry or GEOMETRYCOLLECTION. The index is 1-based.

SQL
ST_GeometryN(geometry g, integer n)geometry

Also works for single geometries — returns the geometry itself when n = 1, or NULL otherwise. For polygons, ST_GeometryN does not walk into rings; use ST_InteriorRingN or ST_DumpRings for that.

When would you use ST_GeometryN?

Use ST_GeometryN to pick a specific component from a multi-geometry — most often the first polygon of a MULTIPOLYGON, the primary component of a GEOMETRYCOLLECTION, or the last segment of a line group:

SQL
1SELECT id,
2       ST_GeometryN(geom, 1) AS primary_polygon
3FROM administrative_regions
4WHERE GeometryType(geom) = 'MULTIPOLYGON';

For iterating all components prefer ST_Dump, which is usually both more idiomatic and more efficient than a loop of ST_GeometryN calls.

FAQs

Is ST_GeometryN 0- or 1-based?

1-based. ST_GeometryN(mp, 1) returns the first component. Indices outside the range return NULL.

Does ST_GeometryN recurse into nested collections?

No. It only returns top-level components. For nested GEOMETRYCOLLECTIONs use ST_Dump to flatten first.

What is the difference between ST_GeometryN and ST_PatchN?

ST_GeometryN works on multi-geometries and collections of simple geometries. ST_PatchN works on POLYHEDRALSURFACE and returns individual patch polygons.

How do I count total components?

Use ST_NumGeometries. A typical pattern is SELECT ST_GeometryN(g, generate_series(1, ST_NumGeometries(g))) but ST_Dump is simpler for bulk iteration.