Question

Here is the SQL, 'aal_county_zip' has entry for 2 zipcodes whereas 'us_zip' has 15 zipcodes. The requirement is to get 15 rows with only 2 rows having data from 'aal_county_zip'. It works like a normal join. How can I make change the SQL/Table structure to make this work. I also want to add the condition that is commented below.

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 ) 
WHERE  Lower(c.name) = Lower('alachua') 
--and c.report_year=2009 
ORDER  BY c.report_year DESC 
Was it helpful?

Solution

The WHERE Lower(c.name) = Lower('alachua') in your query turns the outer join into an inner join, since it prevents c.name from being NULL.

Consider using a left join instead, as they're often more natural to write. And in any event, apply that condition to the join clause rather than to the where clause, so as to avoid turning it into an inner join.

Borrowing and amending @dasblinkenlight's query:

SELECT DISTINCT
    a.zcta5ce10 AS zipcode
,   c.report_year
,   c.aal 
FROM  us_zip a
LEFT OUTER JOIN aal_county_zip c
      ON c.zip = a.zcta5ce10
     AND c.report_year=2009 
     AND LOWER(c.name) = LOWER('alachua') 
ORDER BY c.report_year DESC

That should fix your "only two rows returned" problem. That said, the query is likely missing some additional criteria (and ordering criteria) on us_zip.

OTHER TIPS

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 ) 
WHERE  Lower(c.name) = Lower('alachua') 
  AND  COALESCE(c.report_year, 2009)=2009
ORDER  BY c.report_year DESC 

or

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 AND c.report_year=2009) 
WHERE  Lower(c.name) = Lower('alachua') 
ORDER  BY c.report_year DESC 

You're doing a RIGHT OUTER JOIN, so your first table, aal_county_zip, may contain nulls. So either you account for those nulls by using COALESCE, or you make it part of the join condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top