← Questions

Total population of a city across zip codes in SQL

0
NvidiaCodingLast asked Feb 2026

A coding interview question asked in Nvidia's technical phone screen, last asked Feb 2026. It tests sql, joins and aggregation.

Four tables describe geography, each row pointing to its parent:

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

Population is stored per zip code. Write SQL that returns the total population of a city given its name, summed over all of the city's zip codes. The same city name can exist in several states or countries, and your query must not silently merge them.

Example

country: (1, 'USA'), (2, 'Canada')
state:   (10, 1, 'Oregon'), (11, 1, 'Maine'), (20, 2, 'Ontario')
city:    (100, 10, 'Portland'), (101, 11, 'Portland'), (102, 20, 'London')
zip:     ('97201', 100, 15000), ('97202', 100, 25000),
         ('04101', 101, 20000), ('N6A', 102, 30000)

city name = 'Portland'
->  country | state  | city     | total_population
    USA     | Oregon | Portland | 40000
    USA     | Maine  | Portland | 20000

Constraints

  • The city name arrives as a parameter (:city_name).
  • A city with no zip rows should still be considered: decide whether it appears with 0 or not at all.

Clarifying questions

  • Should several cities with the same name come back as separate rows, or is the caller expected to pass a state and country too?
  • Should a city with no zip codes return 0?
  • Is the name match case-sensitive, and can names have trailing spaces?
  • Can a zip code belong to more than one city?

What a strong answer covers

  • Joins from city to zip for the sum and to state and country to identify each city; grouping by city_id (not by name) so same-named cities stay separate.
  • LEFT JOIN with COALESCE(SUM(z.population), 0) if cities without zip rows must show 0.
  • A variant that takes city, state and country names to return exactly one row.
  • Indexes that make it fast (city(name), zip(city_id)), and common mistakes: grouping by name, filtering on an alias in WHERE, double counting from a bad join.

Follow-ups

  • Return the most populous city in each state.
  • Return each state's population and its share of the country's total.
  • A zip code can span several cities with a population split: how do you model and query it?

Where it's asked

What it tests

sql · joins · aggregation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding