Difficulty: Intermediate · Estimated time: 15 min Schema:
00_Sample_Schema.sql
A three-table join (employees → departments → locations) used to
build a human-readable label column. This lesson’s real lesson is
scalability of WHEN branches — the original two-city version
doesn’t generalize, and that’s the point.
CASE labels across a multi-hop joinWHEN branches become a maintenance liabilityCONCATHR dashboards and workforce reports are read by people, not systems —
“Nagpur Employee” is a label a regional VP can scan in a table of 500
rows; location_id = 1 is not.
See 04_Employee_Labelling.sql.
'Nagpur Employee' and 'Pune Employee' — because it has an
explicit WHEN for Nagpur and dumps everything else into ELSE
'Pune Employee'. Once a third city (Indore, present in the seed
data) enters the picture, every Indore employee is mislabeled as
Pune. This is flagged explicitly here because it’s a very common
production bug: an ELSE branch that was written when only two
categories existed silently absorbs every new category added later.WHEN branches — it’s recognizing that
city || ' Employee' needs no CASE at all when the label is a
pure, mechanical transformation of an existing column.CASE when the mapping from input to output is not a
1:1 mechanical transformation (i.e. there’s real business logic:
thresholds, groupings, exceptions). When it is 1:1, string
concatenation is simpler, automatically correct for new values, and
easier to read.ELSE 'Other Location', never a valid-sounding
city name.| Mistake | Consequence |
|---|---|
ELSE re-using a real value (‘Pune Employee’) as the fallback |
Every new/unanticipated category is silently mislabeled as an existing one — the most dangerous kind of CASE bug because it produces no error, just wrong data |
Hardcoding every known value as a WHEN branch |
Doesn’t scale; breaks the moment a new value is added upstream |
ELSE fallback?CASE for a labelling task?03_City_Analysis.md05_Business_Rules.md10_String_Functions