NOT IN vs IN Do Not Return Complimentary Results

后端 未结 4 1026
灰色年华
灰色年华 2021-02-11 10:03

Hi I am working through example #7 from the sql zoo tutorial: SELECT within SELECT. In the following question

\"Find each country that belongs to a continent where all p

4条回答
  •  你的背包
    2021-02-11 10:27

    If I'm reading this correctly, the question asks to list every country in a continent where every country has a population below 25000000, correct?

    If yes, look at your sub query:

    SELECT continent FROM world
    WHERE population > 25000000
    

    You are pulling every continent that has at least one country w/ population over 25000000, so excluding those is why it works.

    Example: Continent Alpha has 5 countries, four of them are small, but one of them, country Charlie has a population of 50000000.

    So your sub query will return Continent Alpha because country Charlie fit the constraint of population > 25000000. This sub query will find everything that you don't want, that's why using the not in will work.

    On the other hand:

    SELECT continent FROM world
    WHERE population > 25000000
    

    If ANY country is below 25000000, it will display the continent, which is not what you want, because you want EVERY country to be below.

    Example: Continent Alpha from before, the four small countries. Those four are below 25000000, so they will be returned by your sub query, regardless of the fact that Country Charlie has 50000000.

    Obviously, this is not the best way to go about it, but this is why the first query worked, and the second did not.

提交回复
热议问题