
Composing and decomposing Multi-geometries
There are two functions designed for creating Multi-geometries:
- The first one, ST_Multi, is used for converting a single geometry into a single-part Multi-geometry:
SELECT ST_AsText(ST_Multi(ST_MakePoint(391390,5817855)))
MULTIPOINT((391390,5817855))
This is useful in situations where the database design enforces a uniform geometry type across the whole table, and single geometries cannot be stored alongside Multi-geometries.
To create a multi-part Multi-geometry, another function called ST_Collect must be used.
The simplest use case is to merge two single geometries into a single Multi-geometry. For that, ST_Collect can accept two arguments of the geometry type:
SELECT
ST_Collect(ST_MakePoint(20,50),ST_MakePoint(19.95,49.98));
For more complex MultiPoints, there are two possibilities. The first one is to pass the PostgreSQL ARRAY of geometries as the argument to ST_Collect:
SELECT
ST_Collect(ARRAY[ST_MakePoint(20,50),ST_MakePoint(19.95,49.98),
ST_MakePoint(19.90,49.96)]);
- The second option is to use ST_Collect as an aggregate function, just like SUM or AVG are used for numbers. For example, to collect POI groups into MultiPoints, you can do the following:
SELECT amenity, ST_Collect(way) FROM planet_osm_point GROUP BY
amenity;
When using ST_Collect as an aggregate, the standard rules of using aggregate functions in PostgreSQL apply: All other columns must be used in another aggregate (SUM, AVG, string_agg, array_agg, and so on) or in a GROUP BY clause. Failure to do so will result in an error:
SELECT tourism, amenity, ST_Collect(way) FROM planet_osm_point
GROUP BY amenity;
ERROR: column planet_osm_point.tourism must appear in the
GROUP BY clause or be used in an aggregate function.