KatInterview

Aggregate ZIP-Level Population Data with SQL Joins

SQL & DataModel answer
EasyModel answerSQL & Datasqljoinsaggregation

Last updated

Write a SQL query to compute total city population by summing ZIP code records, handling joins and duplicate city names across regions.

You are working with a normalized geographic database containing four tables:

country(country_id, name)
state(state_id, country_id, name)
city(city_id, state_id, name)
zip(zip_code, city_id, population)

Population data is stored at the ZIP code level in the zip table.

Part A: Write a SQL query that accepts a city name as input (:city_name) and returns the total population for that city by summing all ZIP code populations belonging to it.

Part B: Explain how you would handle the fact that multiple cities can share the same name across different states or countries (for example, "Springfield" exists in many U.S. states). What changes would you make to your query or API design?

Your answer should include:

  • The SQL query (or multiple variations)
  • An explanation of your join strategy
  • How you avoid common pitfalls like double-counting or dropped records
  • Your approach to the duplicate-name problem

Hints

Hint 1

Population must be summed from the zip table, which means you need to join from city to zip and aggregate the results.

Hint 2

City names are not unique identifiers—there can be many cities with the same name in different locations. Consider whether to return multiple rows or require additional filters.

Hint 3

Think about what happens when a city has no ZIP code records. Should it appear in the result with zero population or be omitted entirely?