Skip to content
Advertisement

PostgreSQL query to select postcodes where where there are no properties

enter image description hereI have a two tables:

properties

  • uid
  • source
  • postcode

postcodes

  • postcode

What I’m trying to do is make a list of postcodes that have no properties grouping them by source and postcode, I had a partial success with this query:

The problem is that is returning me null sources and what I need is to know which sources have no properties with that postcode.

Need a result like this:

count postcode source

0 “AB10 1AB” zoopla

10 “AB10 1AB” openrent

0 “AB10 1AB” spareroom

Advertisement

Answer

If you just want postcodes with no properties, use not exists:

If the postcodes have no properties, there is no corresponding source.

If you want a list of sources/postcode pairs, then use a cross join to get all combinations and the same basic logic:

If you have a separate table of sources, use that instead of the subquery.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement