SQL-Engineering-Handbook

03 · City Analysis

Difficulty: Intermediate · Estimated time: 15 min Schema: 00_Sample_Schema.sql

City department demand

Introduction

Same shape as Lesson 02 (CASE over an aggregate), applied to a multi-table join across locations → departments. This lesson focuses on what happens to CASE classification when the underlying join can fan out or drop rows.

Learning Objectives

Business Context

Expansion and resource-allocation decisions (“should we open a second office in this city?”) are often driven by exactly this kind of department-concentration metric.

SQL

See 03_City_Analysis.sql.

Engineering Notes

Best Practices

Common Mistakes

Interview Questions

  1. Why might a city with genuinely zero departments not appear in this report at all?
  2. How would you rewrite the query so every city always appears, even with zero departments?
Answers 1. The `INNER JOIN` between `locations` and `departments` requires a match; a city with no departments produces no joined rows and is dropped before `GROUP BY` even runs. 2. Switch to `LEFT JOIN locations l ... departments d ON l.location_id = d.location_id`, and wrap the count with `COALESCE(COUNT(d.dept_id), 0)` so it doesn't null out.

Cross References