Home > Back-end >  need help understanding elements of these SQL ZOO queries
need help understanding elements of these SQL ZOO queries

Time:02-01

In these two sql zoo questions, there's this where clause i don't understand:

Question 1:

"Some countries have populations more than three times that of all of their neighbors (in the same continent). Give the countries and continents."

answer:

select name, continent
from world x
where population/3 >= ALL(select population from world y where y.continent=x.continent and y.name <> x.name)

Question 2:

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.

answer:

SELECT name, continent, population 
FROM world x 
WHERE 25000000>=ALL (SELECT population FROM world y WHERE x.continent=y.continent AND population>0)

in the context of these two questions, what does y.continent=x.continent do? Does it server as some kind of join? Without it, the query fails, but I don't fully understand why.

CodePudding user response:

Format your query so that you can read it easier and get a grasp of what is going on.

select name, 
       continent 
from world x 
where population / 3 >= ALL(select population 
                            from world y 
                            where y.continent=x.continent 
                            and y.name <> x.name)

Your question is

"Some countries have populations more than three times that of all of their neighbours (in the same continent). Give the countries and continents."

Theres two things you have to do here. You have to get all the populations and divide by three, then find all the populations that are equal to or greater than. Those will be the ones that are three times greater pop.

The x.continent = y.continent makes sure you are comparing only ones on the same continent.

  •  Tags:  
  • Related