Skip to content
Advertisement

Getting different results from Subquery and JOIN which seem to be the same

I’m doing a challenge problem on DataCamp. It uses two tables, “economies” which contains economic information by country code, and “countries” which contains general country information by country code.

The challenge is: Get country code, inflation rate, and unemployment rate in 2015 from the “economies” table, where the gov_form is not ‘Constitutional Monarchy’ or ‘%Republic%’ in the “countries” table.

With a LEFT JOIN I get 20 results:

With a subquery I get 26 results:

It seems that the JOIN version is excluding countries that do not exist in the “countries” table (they only exist in the “economies” table), for example ROU(Romania). However, I thought LEFT JOIN with “economies” on the left would include all rows from that table and not drop them regardless of whether they exist in the right table?

Any advice is appreciated.

Advertisement

Answer

In the first query you destroy the effect of the left join by putting conditions on the fields of the joined table. For example, c.gov_form <> 'Constitutional Monarchy' will be false when there is no country record that fulfills the join condition, because then c.gov_form is null.

Solve this by moving those conditions into the join on clause:

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