The ST_Difference() function

The ST_Difference() function takes two geometry objects and returns a geometry object that is the difference of the source objects. In other words, it returns the portion of the primary geometry that is not intersected by the secondary geometry, the logical AND NOT of space.

Syntax

ST_Difference(g1 ST_Geometry, g2 ST_Geometry)

Usage

The ST_Difference() function operates only on geometries of like dimension and returns an ST_GeomCollection (ST_MultiPoint, ST_MultiLineString, or ST_MultiPolygon) that has the same dimension as the source geometries. If the source geometries are equal, an empty geometry is returned.
Figure 1: The ST_Difference() function

This graphic shows the difference between various geometric objects.

Return type

ST_Geometry

Example

The city engineer needs to know the total city lot area that is not covered by buildings. In fact, the engineer wants the sum of the lot area after the building area is removed:
CREATE TABLE buildingfootprints (building_id  integer,
                                 lot_id       integer,
                                 footprint    ST_MultiPolygon);

CREATE TABLE lots (lot_id  integer,
                   lot     ST_MultiPolygon);
The city engineer equijoins the buildingfootprints and lots tables on the lot_id column and takes the sum of the area of the difference of the lots less the building footprints:
SELECT SUM(ST_Area(ST_Difference(lot,footprint)::ST_MultiPolygon))
   FROM buildingfootprints bf, lots
   WHERE bf.lot_id = lots.lot_id;