Merging polygons using a common attribute
There are many cases in GIS workflows where you need to merge a polygonal dataset based on a common attribute. A typical example is merging the European administrative areas (that you can see at http://en.wikipedia.org/wiki/Nomenclature_of_Territorial_Units_for_Statistics), starting from the NUTS level 4 to obtain the subsequent levels up to the NUTS level 1, using the NUTS code or merging the USA counties layer using the state code to obtain the states layer.
PostGIS lets you perform this kind of processing operation with the ST_Union
function.
Getting ready
Download the USA counties shapefile from the nationalatlas.gov website at http://dds.cr.usgs.gov/pub/data/nationalatlas/co2000p020_nt00157.tar.gz (this archive is also included in the code bundle provided with this book) and import it in PostGIS as follows:
$ ogr2ogr -f PostgreSQL -s_srs EPSG:4269 -t_srs EPSG:4326 -lco GEOMETRY_NAME=the_geom -nln chp03.counties -nlt MULTIPOLYGON PG:"dbname='postgis_cookbook...