I have a PostgreSQL 9.6 table that looks like this:
range (string) count suburb
-------------- ------ ------
< 200,000 1 NEDLANDS
400,000 to 599,000 4 NEDLANDS
600,000 to 799,000 5 NEDLANDS
> 2 1 NEDLANDS
If a range's count is 0, there's no record in the table, but I want my query to return every range and report 0 where no record exists. So, for the above table, the desired result set would be:
range (string) count
-------------- ------
<200,000 1
200,000 to 400,000 0
400,000 to 599,000 4
600,000 to 799,000 5
800,000 to 1m 0
1m > 2m 0
> 2 1
I thought I could union the query that finds the records with a query that doesn't find the records, but my query is still does not find 0-count records:
select range, count
from sales
where suburb = 'NEDLANDS'
union all
select range, 0 as count from sales
where not exists (select range, count
from sales
where suburb = 'NEDLANDS' );
Is there something I'm missing?