Search code examples
sqlpostgresqlouter-joinright-join

sql left outer join with a constraining column


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 

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.