sqlaggregation

Why SQL HAVING SUM(column) comparison with number does not work?


Try to find the continents where all countries have a population <= 25000000 from the world table below as in Difficult Questions That Utilize Techniques Not Covered In Prior Sections.

name continent area population gdp
Afghanistan Asia 652230 25500100 20343000000
Albania Europe 28748 2831741 12960000000
Algeria Africa 2381741 37100000 188681000000
Andorra Europe 468 78115 3712000000
Angola Africa 1246700 20609294 100990000000
...

The SQL below returns nothing but not sure why. Please advise.

SELECT 
    continent, 
    SUM(population) as total
FROM 
    world
GROUP BY 
    continent
HAVING SUM(population) <= 25000000

Without HAVING, it returns rows as below:

SELECT 
    continent, 
    SUM(population) as total
FROM 
    world
GROUP BY 
    continent
/* HAVING SUM(population) <= 25000000 */
continent total
Africa 1016091005
Asia 4342955676
Caribbean 36149204
Eurasia 149017400
Europe 610261850
North America 518755156
Oceania 37783477
South America 407618970

Solution

  • Because none of the populations added up for the continents is less than 25,000,000. The smallest is Caribbean at 36,149,204

    Did you mean to have HAVING SUM(population) <= 250000000 (one more zero)

    Then you would get three rows returned.

    However the question asks you to return "Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.". So your query doesn't do this.

    The correct answer can be found by looking for a continent where any of the countries populations (not the total of them) exceed the number and excluding those continents using a NOT IN

    SELECT name, continent, population
    FROM world
    WHERE Continent NOT IN
    (
    SELECT DISTINCT Continent
    FROM world
    WHERE population > 25000000
    )
    

    There probably is also a way to do it using the ALL clause, which is probably what they wanted.