CASE Inside Aggregates for Buckets
Bucket employees into salary bands and count how many fall in each.
Overview
CASE combined with COUNT and GROUP BY lets you build histogram-style
buckets directly in SQL. Here we classify each employee into a salary band (under
70k, 70-90k, 90-110k, and 110k-plus) and count how many employees land in each
band.
The Query
Employees & Departments
Loading database engine...
Step-by-Step Breakdown
CASE— maps each salary to a band label using orderedWHENbranches.COUNT(*)— tallies employees per band.GROUP BY salary_band— one row per distinct band label produced.
Order matters in CASE
CASE evaluates WHEN branches top-to-bottom and stops at the first match,
so list bands in increasing (or decreasing) order to avoid overlap bugs.
Variations
Bucket movies by decade:
Movies (Movies/Actors/Ratings)
Loading database engine...
Common Mistakes
- Overlapping WHEN clauses. Because
CASEstops at the first match, an out-of-order range can silently misclassify rows. - Non-grouped CASE column in SELECT. The exact
CASEexpression must appear inGROUP BY(or be aliased consistently). - Missing ELSE. Rows matching no
WHENbecomeNULL; group them intentionally if needed.