Name

ST_SymDifference — Computes a geometry representing the portions of geometries A and B that do not intersect.

Synopsis

geometry ST_SymDifference(geometry geomA, geometry geomB, float8 gridSize = -1);

Description

Returns a geometry representing the portions of geometries A and B that do not intersect. This is equivalent to ST_Union(A,B) - ST_Intersection(A,B). It is called a symmetric difference because ST_SymDifference(A,B) = ST_SymDifference(B,A).

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

Performed by the GEOS module

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.21

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

Examples

This example shows a 2D-safe symmetric difference of two LineStrings.

Code
SELECT ST_SymDifference('LINESTRING(50 100,50 200)',
        'LINESTRING(50 50,50 150)'
    );
Output
MULTILINESTRING((50 150,50 200),(50 50,50 100))
Figure
Geometry figure for visual-st-symdifference-01

In 3D, this example does not produce the expected result.

Code
SELECT ST_SymDifference('LINESTRING(1 2 1,1 4 2)',
    'LINESTRING(1 1 3,1 3 4)');
Output
MULTILINESTRING((1 3 4,1 4 2),(1 1 3,1 2 1))
Figure
Geometry figure for visual-st-symdifference-02

To measure the area covered by exactly one of two sets of polygons, first dissolve each set with the aggregate form of ST_Union. Then compute the symmetric difference once between the two dissolved coverages.

Code
WITH old_areas(geom) AS (
  VALUES (ST_MakeEnvelope(0, 0, 2, 2)),
         (ST_MakeEnvelope(2, 0, 4, 2))
),
new_areas(geom) AS (
  VALUES (ST_MakeEnvelope(1, 0, 3, 2)),
         (ST_MakeEnvelope(3, 0, 5, 2))
)
SELECT ST_Area(ST_SymDifference(old_cover.geom, new_cover.geom))
       AS changed_area
FROM (SELECT ST_Union(geom) AS geom FROM old_areas) AS old_cover
CROSS JOIN (SELECT ST_Union(geom) AS geom FROM new_areas) AS new_cover;
Output
4
Figure
Geometry figure for visual-st-symdifference-03