I'm testing various SQL queries to do a seemingly easy ST_Difference in PostGIS. It needs to be done in SQL as I'm testing to later use the query on quite large datasets.
Original code I tried:
CREATE TABLE test_diff (
geom geometry(MultiPolygon, 2154)
);
CREATE INDEX idx_test_diff_geom
ON test_diff
USING GIST (geom);
INSERT INTO test_diff (geom)
SELECT ST_CollectionExtract(ST_Difference(a.geom, b.geom), 3)::geometry(MultiPolygon, 2154)
FROM test_st_diff1 AS a
JOIN test_st_diff2 AS b
ON ST_Intersects(a.geom, b.geom);
This works, but only on the polygons that intersect each other. I want those who don't intersect to also get 'cut'.
So I tried the next code to try to fix it:
CREATE TABLE test_diff_result AS
SELECT ST_Difference(a.geom, b.geom) AS geom
FROM test_st_diff1 AS a, test_st_diff2 AS b;
The problem with this one is that it doesn't affect the first dataset at all.