Summary
SQL Population Census - Summary
In this tutorial, we will perform a population census using SQL by joining the city and country tables available on HackerRank. The two tables are linked through the country code, where city.country_code matches country.code. Our goal is to query the sum of populations for all cities located in the continent of Asia.
Steps to Create the Query
-
Identify Tables: The
citytable contains population data, but does not have continent information. We will need to join it with thecountrytable, which has the continent data. -
Join Tables: We will use an inner join, which selects records that have matching values in both tables. The inner join will allow us to filter the cities based on their corresponding countries.
-
Filter Records: To focus only on the cities in Asia, we will filter the records from the
countrytable by where the continent is 'Asia'. -
Select and Sum: We will use the
SUMfunction to calculate the total population from thecitytable, ensuring we specifycity.populationto avoid ambiguity with any similar column names in thecountrytable. -
Final Query: The completed SQL query will look something like this:
SELECT SUM(city.population)
FROM city
INNER JOIN country ON country.code = city.country_code
WHERE country.continent = 'Asia';
After executing the query, we will obtain the total population of all cities located in Asia.