Name

ST_Difference — Returns a geometry that represents that part of geometry A that does not intersect with geometry B.

Synopsis

geometry ST_Difference(geometry geomA, geometry geomB);

Description

Returns a geometry that represents that part of geometry A that does not intersect with geometry B. One can think of this as GeometryA - ST_Intersection(A,B). If A is completely contained in B then an empty geometry collection is returned.

[Note]

Order matters. B - A will always return a portion of B

Performed by the GEOS module

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

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

This function supports 3d and will not drop the z-index. However it seems to only consider x y when doing the difference and tacks back on the Z-Index

Examples

The original linestrings shown together.

The difference of the two linestrings

Safe for 2D. This is same geometries as what is shown for st_symdifference

SELECT ST_AsText(
	ST_Difference(
			'LINESTRING(50 100, 50 200)'::geometry,
			'LINESTRING(50 50, 50 150)'::geometry
		)
	);

st_astext
---------
LINESTRING(50 150,50 200)

When used in 3d doesn't quite do the right thing.

select ST_AsEWKT(
           ST_Difference(
               'MULTIPOINT(-118.58 38.38 5,-118.60 38.329 6,-118.614 38.281 7)' :: geometry,
               'POINT(-118.614 38.281 5)' :: geometry
               )
    );
st_asewkt
---------
MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)

See Also

ST_SymDifference, ST_Intersection, ST_Union