3

I am fiddling around with this dataset http://s3.cleverelephant.ca/postgis-workshop-2020.zip. It is used in this workshop http://postgis.net/workshops/postgis-intro/spatial_relationships.html.

I want to identify all the census blocks, that do not have a subway station. I thought this spatial join is rather straight forward

SELECT
  census.boroname,
  census.geom
FROM nyc_census_blocks AS census
    JOIN nyc_subway_stations AS subway
        ON ST_Disjoint(census.geom, subway.geom);

However, the result set is way too large.

Why can't I identify all the census blocks that do not have a subway station?

I want to use ST_Disjoint() and not ST_Intersects()

2 Answers 2

3

You are comparing each station to each census block and for each one returning all but one census block.

To fix this you need to union your stations together and then find the disjoint polygons.

SELECT
  census.boroname,
  census.geom
FROM nyc_census_blocks AS census
    JOIN (select st_union(geom) as geom from nyc_subway_stations) subway
        ON ST_Disjoint(census.geom, subway.geom);
0
3

Joining on non-intersection is tricky. An INNER JOIN gathers a set of all matching rows between the tables; in this case, a single row in census matches with every row in subway that has an ST_Disjoint geometry!

In fact, it is better to tackle this the other way around, using ST_Intersects and an EXISTS condition:

SELECT census.boroname,
       census.geom
FROM   nyc_census_blocks AS census
WHERE  NOT EXISTS (
  SELECT 1
  FROM   nyc_subway_stations AS subway
  WHERE  ST_Intersects(census.geom, subway.geom)
);

Alternatively, you could SELECT DISTINCT, but the JOIN is still highly inefficient.

4
  • Hmm, okay, that explains why it is so inefficient. However, I still want to run it with ST_Disjoint() in order to understand it. When I run the query from my Q, I get a table with many rows (that you explained why). However, when I visualize the result, there are only three geometries (census blocks) on the map... That should be way more. Why is that?
    – four-eyes
    Jul 29, 2021 at 7:58
  • @Stophface visualizing this query, or the one in your question?
    – geozelot
    Jul 29, 2021 at 8:21
  • The query in my Q.
    – four-eyes
    Jul 29, 2021 at 8:31
  • 2
    How do you visualize, using QGIS? In theory you should see the full coverage of census geometries - albeit duplicated some 490 times each. In practice, one does not simply render 18 million geometries - especially not from a cached query (note that QGIS will rerun the query each time you change the canvas).
    – geozelot
    Jul 29, 2021 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.