[GIS] Comparing two tables, using PostgreSQL Intersect (on PostGIS geometry)

postgis

I am trying to compare two tables, that are suppose to be equal. One is a reference table (with the "correct" values) and the other is a test output. That is, they have same columns and columntypes. I then want to find the rows that are "identical".
I figured that PostgreSQL's' Intersect (or maybe its opposite, Except) would work here, since it selects rows that appear in both tables.

This works fine if I give it rows that are completely the same:

select 2, ST_Polygon(st_geomfromtext('LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)'), 4326) 
intersect
select 2, ST_Polygon(st_geomfromtext('LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)'), 4326)

returns:

row 1: 2;0103000020E6100000010000000500000000000000000000000000000000000000000000000000F03F0000000000000000000000000000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000000000

However, if the start/end vertex is changed in the geometry column in one of the rows, it returns zero rows:

select 2, ST_Polygon(st_geomfromtext('LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)'), 4326) 
intersect
select 2, ST_Polygon(st_geomfromtext('LINESTRING( 1 0, 1 1, 0 1, 0 0, 1 0)'), 4326)

That is, if i used ST_Equals on the geometries, it would return true. But in Intersect, this is not true.

Is there a smarter way to compare entire tables?

Best Answer

You are mixing non-spatial functionality with spatial objects. PostgreSQL's intersect does not know about spatial. Stay in PostGIS for everything spatial. In other words, use the ST_ functions (Spatial Type) when you work with spatial objects.

For intersections there are ST_Intersects for a boolean condition and ST_Intersection for the geometric intersection.

SELECT ST_Intersects(
  ST_Polygon(ST_GeomFromText('LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)'), 4326),
  ST_Polygon(ST_GeomFromText('LINESTRING(1 0, 1 1, 0 1, 0 0, 1 0)'), 4326)
);
Related Question