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
city
table contains population data, but does not have continent information. We will need to join it with thecountry
table, 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
country
table by where the continent is 'Asia'. -
Select and Sum: We will use the
SUM
function to calculate the total population from thecity
table, ensuring we specifycity.population
to avoid ambiguity with any similar column names in thecountry
table. -
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.