Aggregate ZIP-Level Population Data with SQL Joins
SQL & DataModel answerLast 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?
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core task is to traverse from the city table to the zip table, filter by city name, and aggregate population values. Since population is stored only at the ZIP level, we must sum across all ZIP code rows that belong to the target city.
The critical insight is that city names are not unique. Springfield, for instance, appears in dozens of states. A naive query that sums all ZIP populations where city.name = 'Springfield' would combine unrelated municipalities into a single meaningless number.
There are two clean solutions:
- Return one row per distinct city, disambiguated by state and country names, and let the caller choose.
- Require additional input (state name, country name, or ideally
city_id) to uniquely identify one city.
SQL Queries
Naive Version (Incorrect for Duplicate Names)
SELECT COALESCE(SUM(z.population), 0) AS total_population
FROM city c
LEFT JOIN zip z ON z.city_id = c.city_id
WHERE c.name = :city_name;
This works only if city names are globally unique, which is rarely true in real schemas.
Recommended: Disambiguated Results
SELECT
c.city_id,
c.name AS city_name,
s.name AS state_name,
co.name AS country_name,
COALESCE(SUM(z.population), 0) AS total_population
FROM city c
JOIN state s ON s.state_id = c.state_id
JOIN country co ON co.country_id = s.country_id
LEFT JOIN zip z ON z.city_id = c.city_id
WHERE c.name = :city_name
GROUP BY c.city_id, c.name, s.name, co.name
ORDER BY co.name, s.name;
This query returns one row per matching city, with state and country included so the caller can distinguish them. If zero cities match, the result is empty. If multiple cities match, the caller can pick the correct one or refine the search.
Fully Qualified: Single City Result
SELECT COALESCE(SUM(z.population), 0) AS total_population
FROM city c
JOIN state s ON s.state_id = c.state_id
JOIN country co ON co.country_id = s.country_id
LEFT JOIN zip z ON z.city_id = c.city_id
WHERE c.name = :city_name
AND s.name = :state_name
AND co.name = :country_name;
This version requires the caller to supply state and country names to uniquely identify the city. Even better: accept a city_id directly after a lookup step, avoiding name ambiguity entirely.
Why This Works
- No double-counting. Each city belongs to exactly one state, and each state to exactly one country, so joining
stateandcountryadds columns without duplicating rows. The only one-to-many relationship iscity → zip, which is precisely the fan-out we want to aggregate. - Each ZIP counted once. Since
zip.city_idis a single foreign key, every ZIP belongs to exactly one city. Grouping bycity_idensures different cities with the same name remain separate. - Handling missing ZIPs. The
LEFT JOINensures cities with no ZIP records still appear.COALESCEconverts the NULL fromSUM()over zero rows into 0. - Correct grouping. We group by
city_id, the natural key. Includingc.name,s.name, andco.namein theGROUP BYis required for strict SQL validity, but these columns are functionally dependent on the IDs.
Complexity
Let k be the number of cities matching the name and z the total ZIP rows for those cities.
- Time: O(log N + k + z) with indexes on
city(name),zip(city_id), and primary keys onstateandcountry. Without indexes, O(|city| + |zip|) for full scans and hash joins. - Space: O(k) for the grouped output.
The zip(city_id) index is performance-critical. Note that foreign keys are not automatically indexed in PostgreSQL and some other databases.
Edge Cases and Considerations
- No matching city. The disambiguated query returns an empty result set. The naive query returns one row with
0, which is ambiguous (does the city exist with zero population, or does it not exist at all?). - Duplicate names in the same state. Rare but possible if there's no uniqueness constraint. The query still separates rows by
city_id. AUNIQUE(state_id, name)constraint is advisable if business rules permit. - NULL populations.
SUMignores NULLs. Decide whether NULL means "unknown" (and should be surfaced) or implicitly "zero." - Case sensitivity and whitespace. "new york" vs "New York" may differ depending on collation. Normalize with
LOWER(TRIM(...))or use a case-insensitive collation. Beware that wrapping columns in functions can prevent index use; functional indexes may be needed. - Overflow. Use
BIGINTfor the sum. Large cities can have populations exceeding 32-bit integer limits. - SQL injection. Always use parameterized queries. Never concatenate user input into SQL strings.
Python Implementation
import sqlite3
from typing import Optional
QUERY = """
SELECT
c.city_id,
c.name AS city_name,
s.name AS state_name,
co.name AS country_name,
COALESCE(SUM(z.population), 0) AS total_population
FROM city c
JOIN state s ON s.state_id = c.state_id
JOIN country co ON co.country_id = s.country_id
LEFT JOIN zip z ON z.city_id = c.city_id
WHERE c.name = :city_name
AND (:state_name IS NULL OR s.name = :state_name)
AND (:country_name IS NULL OR co.name = :country_name)
GROUP BY c.city_id, c.name, s.name, co.name
ORDER BY co.name, s.name
"""
def get_city_population(
conn: sqlite3.Connection,
city_name: str,
state_name: Optional[str] = None,
country_name: Optional[str] = None,
) -> list[dict]:
"""
Retrieve population for all cities matching the given name.
Returns one row per distinct city. Empty list means no match.
Multiple rows mean the name is ambiguous.
"""
cursor = conn.execute(
QUERY,
{
"city_name": city_name,
"state_name": state_name,
"country_name": country_name,
},
)
columns = [desc[0] for desc in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
The optional-filter pattern (:param IS NULL OR col = :param) allows one query to handle all cases. The caller interprets the result:
- 0 rows: city not found
- 1 row: unique match
- Multiple rows: ambiguous; prompt for state/country or display choices
What Strong Candidates Demonstrate
- Correct join path and aggregation without hesitation
- Immediate recognition that city names are not unique
- Proposing concrete solutions (grouping by ID, requiring more input, or returning multiple rows)
- Mentioning the
LEFT JOINto preserve cities with no ZIP records - Awareness of indexing, especially on
zip(city_id) - Discussing parameterized queries to prevent SQL injection