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]

Note - order matters. B - A will always return a portion of B

Performed by the GEOS module

[Note]

Do not call with a GeometryCollection as an argument

This method implements the OpenGIS Simple Features Implementation Specification for SQL. OGC SPEC 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(
			ST_GeomFromText('LINESTRING(50 100, 50 200)'),
			ST_GeomFromText('LINESTRING(50 50, 50 150)')
		)
	);

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

--When used in 3d doesn't quite do the right thing
SELECT ST_AsEWKT(ST_Difference(ST_GeomFromEWKT('MULTIPOINT(-118.58 38.38 5,-118.60 38.329 6,-118.614 38.281 7)'), ST_GeomFromEWKT('POINT(-118.614 38.281 5)')));
st_asewkt
---------
MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)
		

See Also

ST_SymDifference