ST_Difference
What is ST_Difference?
ST_Difference returns the part of geometry g1 that does not lie within geometry g2 — the set-theoretic difference g1 \ g2. The result is the "remainder" of g1 after subtracting everything it shares with g2.
1ST_Difference(geometry g1, geometry g2) → geometry
2ST_Difference(geometry g1, geometry g2, float gridSize) → geometryThe optional gridSize (PostGIS 3.1+) snaps inputs to a fixed precision grid before computing, which makes the overlay more robust against near-coincident vertices.
When would you use ST_Difference?
Use ST_Difference to remove one area from another: subtracting water bodies from a country polygon to get land-only, excluding parks and cemeteries from a developable-land layer, or producing buffer zones with holes cut out for existing features. In linear networks it removes already-processed segments; in point sets it filters out points falling within exclusion zones.
1-- Developable land = municipality minus parks and water
2SELECT m.id,
3 ST_Difference(m.geom, ST_Union(p.geom)) AS developable
4FROM municipalities m
5LEFT JOIN protected_areas p ON ST_Intersects(m.geom, p.geom)
6GROUP BY m.id, m.geom;FAQs
Is ST_Difference symmetric?
No. ST_Difference(a, b) returns the part of a not in b; ST_Difference(b, a) returns the part of b not in a. For the symmetric difference (parts in exactly one of the two), use ST_SymDifference.
What units does the gridSize parameter use?
The CRS units of the inputs. A typical value for metre-based data is 0.001 (1 mm) to suppress tiny floating-point slivers; for lat/lon data it is best to reproject first rather than snap on degrees.
Does ST_Difference use a spatial index?
Not directly on a single pair. In JOINs, filter candidates first with ST_Intersects (which uses the index) to avoid calling ST_Difference on non-overlapping pairs. Pre-aggregate with ST_Union when subtracting many geometries from one target.
What about 3D?
ST_Difference is a 2D operation — Z and M values are dropped or handled inconsistently. For true 3D differences use SFCGAL functions such as ST_3DDifference.