Skip to content
SQLSimplified
case

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

  1. CASE — maps each salary to a band label using ordered WHEN branches.
  2. COUNT(*) — tallies employees per band.
  3. 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 CASE stops at the first match, an out-of-order range can silently misclassify rows.
  • Non-grouped CASE column in SELECT. The exact CASE expression must appear in GROUP BY (or be aliased consistently).
  • Missing ELSE. Rows matching no WHEN become NULL; group them intentionally if needed.

Search

Search lessons, functions, examples, and practice problems