ST_Difference

Calculates the part of a spatial object that does not intersect with another spatial object.

Behavior Type

Immutable

Syntax

ST_Difference( g1, g2 )

Arguments

g1

Spatial object, type GEOMETRY

g2

Spatial object, type GEOMETRY

Returns

GEOMETRY

Supported Data Types

Data Type GEOMETRY
Point Yes
Multipoint Yes
Linestring

Yes

Multilinestring

Yes

Polygon

Yes

Multipolygon

Yes

GeometryCollection

Yes

Examples

The following examples show how to use ST_Difference.

Two overlapping linestrings:

=> SELECT ST_AsText(ST_Difference(ST_GeomFromText('LINESTRING(0 0,0 2)'),
   ST_GeomFromText('LINESTRING(0 1,0 2)')));
       ST_AsText      
-----------------------
 LINESTRING (0 0, 0 1) (1 row) => SELECT ST_AsText(ST_Difference(ST_GeomFromText('LINESTRING(0 0,0 3)'), ST_GeomFromText('LINESTRING(0 1,0 2)'))); ST_AsText ------------------------------------------ MULTILINESTRING ((0 0, 0 1), (0 2, 0 3)) (1 row)

Two overlapping polygons:

=> SELECT ST_AsText(ST_Difference(ST_GeomFromText('POLYGON((0 1,0 3,2 3,2 1,0 1))'),
   ST_GeomFromText('POLYGON((0 0,0 2,2 2,2 0,0 0))')));
            ST_AsText
-------------------------------------
 POLYGON ((0 2, 0 3, 2 3, 2 2, 0 2))
(1 row)

Two non-intersecting polygons:

=> SELECT ST_AsText(ST_Difference(ST_GeomFromText('POLYGON((1 1,1 3,3 3,3 1,
   1 1))'),ST_GeomFromText('POLYGON((1 5,1 7,-1 7,-1 5,1 5))')));
              ST_AsText              
-------------------------------------
 POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))
(1 row)