[GIS] How to deal with “ERROR: GEOSUnaryUnion: TopologyException: Self-intersection”

postgispostgresql

I'm using Postgres 9.4 and PostGIS 2.1. My table looks like this:

------------------------------------------------------------------
 ogc_fid      | integer                | not null default
 wkb_geometry | geometry(Polygon,4326) |
 county       | character varying      |

I am trying to create the union of several thousand polygon fields:

select ST_UNION(wkb_geometry) from mytable where county='Glos';

But I get this error:

ERROR:  GEOSUnaryUnion: TopologyException: Input geom 0 is invalid: 
Self-intersection at or near point -2.3936967722194602 51.540060494135503 at -2.3936967722194602 51.540060494135503

Why could this be happening? And what can I do about it? Is there a way that I can check whether the input polygons are valid?

I don't mind if the fields overlap: I just need to merge them all down (as it were) to create the overall union.

UPDATE: I'm trying this:

SELECT ogc_fid, ST_isValidReason(wkb_geometry) FROM mytable WHERE (county='Glos') AND (NOT ST_isValid(wkb_geometry));

Results:

   ogc_fid |                      st_isvalidreason
-----------+------------------------------------------------------------
  53270254 | Ring Self-intersection[-2.42234450631667 51.5302222606785]
  20669431 | Ring Self-intersection[-2.42680440846532 51.5321194786993]
  20851050 | Self-intersection[-2.39369677221946 51.5400604941355] 

Best Answer

I ended up using the following query:

UPDATE mytable SET wkb_geometry = ST_MakeValid(wkb_geometry);

As stated in the documentation, already-valid geometries are returned without further intervention.