Data Cleaning Reps

← All guides

From raw numbers to categories: GROUP BY and CASE on real data

A table of 2,628 seismic events isn't an answer. "939 were minor, 1,463 were light, 205 were moderate, and 21 were strong" is an answer. A lot of everyday analysis comes down to two moves: put rows into categories, then count or sum each category. In SQL, those moves are CASE and GROUP BY.

This guide uses two tables from this site: quakes (USGS seismic events from October 2026) and vehicles (FuelEconomy.gov records for model years 2010–2027). As Guide 1 found, two of those rows aren't earthquakes: 2,626 are earthquakes, one is a landslide and one is an explosion. The counts below include all 2,628 so they add up to the table.

GROUP BY: one row per category

GROUP BY collapses all the rows that share a value into one output row. As a reliable habit, every other column you select should be either in the GROUP BY or wrapped in an aggregate, like COUNT, SUM or AVG, so SQL knows how to combine the group. Some databases, SQLite included, will let you select a non-grouped column anyway and return a value from an arbitrary row in the group. That can mislead you, so don't rely on it:

SELECT mag_type, COUNT(*) AS n
FROM quakes
GROUP BY mag_type
ORDER BY n DESC;

Output (real run against the practice database):

mag_typen
mb1538
ml793
mww141
md122
mwr27
mb_lg4
mw2
ms_vx1
8 rows

mag_type records how each magnitude was calculated. There are eight methods in this month of data, and two of them cover most events: mb has 1,538 and ml has 793, together 2,331 of 2,628 (88.7%). The long tail is mww 141, md 122, mwr 27, mb_lg 4, mw 2 and ms_vx 1. That's already a useful finding: if you compare magnitudes, you're mostly comparing two methods, plus a long tail of rarely used ones.

CASE: build the category you need

Often the category you want doesn't exist as a column. Magnitude is a number, but a report wants bands. CASE creates them:

SELECT CASE
         WHEN mag < 4 THEN 'minor (2.5-3.9)'
         WHEN mag < 5 THEN 'light (4.0-4.9)'
         WHEN mag < 6 THEN 'moderate (5.0-5.9)'
         ELSE 'strong (6.0+)'
       END AS band,
       COUNT(*) AS n
FROM quakes
GROUP BY band
ORDER BY MIN(mag);

Output (real run against the practice database):

bandn
minor (2.5-3.9)939
light (4.0-4.9)1463
moderate (5.0-5.9)205
strong (6.0+)21
4 rows

The result is minor 939, light 1,463, moderate 205 and strong 21. To see how CASE gets there, follow one row. Take a magnitude of 4.7:

Step Test Result
1 mag < 4 false (4.7 is not below 4), so keep going
2 mag < 5 true, so the label is light (4.0-4.9) and CASE stops
3 mag < 6 and ELSE never checked

Two details matter here.

Order of the WHEN lines. CASE checks conditions from top to bottom and returns the first match. Because mag < 4 is checked first, the second line only sees magnitudes of 4 and above. So mag < 5 really means "between 4 and 5." Swap the lines and the bands break.

Sorting categories. Sorting by the band name would put them in alphabetical order (light, minor, moderate, strong), which reads badly. ORDER BY MIN(mag) sorts each band by its smallest magnitude instead, so they appear in their natural order without an extra column.

A note on the band names: they're loosely based on common magnitude classes, simplified for the exercise. For a real report, cite the classification you're using.

CASE for cleaning, not just bucketing

CASE is also the everyday tool for collapsing messy labels. The drive column in vehicles uses six labels for what's really three ideas. The counts are All-Wheel Drive 6,964, Rear-Wheel Drive 5,824, Front-Wheel Drive 5,765, 4-Wheel Drive 2,796, Part-time 4-Wheel Drive 761, and one row of 4-Wheel or All-Wheel Drive:

SELECT drive, COUNT(*) AS n
FROM vehicles
GROUP BY drive
ORDER BY n DESC;

Output (real run against the practice database):

driven
All-Wheel Drive6964
Rear-Wheel Drive5824
Front-Wheel Drive5765
4-Wheel Drive2796
Part-time 4-Wheel Drive761
4-Wheel or All-Wheel Drive1
6 rows

"All-Wheel Drive", "4-Wheel Drive", "Part-time 4-Wheel Drive" and the single "4-Wheel or All-Wheel Drive" row all mean that more than two wheels can get power. For most questions, you'd group them together:

SELECT CASE
         WHEN drive LIKE '%4-Wheel%' OR drive LIKE '%All-Wheel%' THEN 'AWD/4WD'
         WHEN drive LIKE 'Front%' THEN 'FWD'
         WHEN drive LIKE 'Rear%' THEN 'RWD'
         ELSE 'Other'
       END AS drive_group,
       COUNT(*) AS n
FROM vehicles
GROUP BY drive_group
ORDER BY n DESC;

Output (real run against the practice database):

drive_groupn
AWD/4WD10522
RWD5824
FWD5765
3 rows

Always include an ELSE branch, even when you think every value is covered. Here, Other doesn't appear in the output, which confirms that the rules caught everything. The result is AWD/4WD 10,522, RWD 5,824 and FWD 5,765, which adds back up to all 22,111 rows. If a new label shows up next year, it lands in Other where you'll notice it, instead of quietly becoming NULL.

Standardization should serve the question you're answering. Combining AWD and 4WD fits "can more than two wheels get power?", but it doesn't fit a comparison of drivetrain technologies, where AWD and 4WD are different things.

CASE and NULL

There's one more trap. If mag were NULL for some row, every WHEN mag < ... test would be unknown, not true, so that row would fall through to the ELSE branch and be labeled "strong." In this table no magnitudes are missing, so the bands are safe. On a column with gaps, add WHEN mag IS NULL THEN 'unknown' as the first branch so missing values get their own honest label instead of hiding inside a real category. It's a small habit that prevents a surprisingly common reporting error.

HAVING: filter the groups, not the rows

WHERE filters rows before grouping. HAVING filters groups after the aggregates are calculated. Which networks reported more than a hundred events?

SELECT net, COUNT(*) AS n
FROM quakes
GROUP BY net
HAVING COUNT(*) > 100
ORDER BY n DESC;

Output (real run against the practice database):

netn
us1997
ak352
2 rows

Two networks qualify: us with 1,997 and ak with 352. The next one, pr, has 95, so it just misses the cutoff. You can't write WHERE COUNT(*) > 100. At the moment WHERE runs, the counts don't exist yet. The same pattern finds models with many records in a single year, which in this table usually means many engine, drive and gearbox combinations:

SELECT make, model, COUNT(*) AS n
FROM vehicles
WHERE year = 2024
GROUP BY make, model
HAVING COUNT(*) >= 8
ORDER BY n DESC, make, model;

Output (real run against the practice database):

makemodeln
ChevroletSilverado 4WD9
ChevroletSilverado Mud Terrain Tires 4WD9
GMCSierra 4WD8
3 rows

Three groups qualify: Chevrolet Silverado 4WD (9), Chevrolet Silverado Mud Terrain Tires 4WD (9) and GMC Sierra 4WD (8). That's 26 of the 1,277 vehicles from 2024. This one combines both filters. WHERE year = 2024 throws out other years first, then HAVING keeps only the big groups. It's also a key-uniqueness check. These rows aren't duplicates, they're legitimate configurations. But make and model alone can't uniquely identify a vehicle, so if you ever join this table to something keyed on make and model, a join on those columns will multiply rows.

Bonus: take it one step further with a percent of total

This section is optional. Counts are easier to read with a share next to them, and a window function can calculate the grand total without a second query. SUM(COUNT(*)) OVER () adds up the group counts across the whole result:

SELECT CASE
         WHEN mag < 4 THEN 'minor (2.5-3.9)'
         WHEN mag < 5 THEN 'light (4.0-4.9)'
         WHEN mag < 6 THEN 'moderate (5.0-5.9)'
         ELSE 'strong (6.0+)'
       END AS band,
       COUNT(*) AS n,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM quakes
GROUP BY band
ORDER BY MIN(mag);

Output (real run against the practice database):

bandnpct
minor (2.5-3.9)93935.7
light (4.0-4.9)146355.7
moderate (5.0-5.9)2057.8
strong (6.0+)210.8
4 rows

The shares are minor 35.7%, light 55.7%, moderate 7.8% and strong 0.8%. The 100.0 again forces decimal division. These four happen to add up to exactly 100.0, but percentages that round to one decimal may not, so mention that if you put them in a table for someone else.

One warning: SUM(COUNT(*)) OVER () only adds up the groups that are left in the result. If you add a WHERE or HAVING filter, the denominator is no longer the whole dataset. For example, put the same pct column on the networks query with HAVING COUNT(*) > 100, and us shows 85.0% and ak 15.0%, because only those two groups are in the total. Against all 2,628 events, us is 76.0%.

Grouping by more than one thing

You can group by several columns, or by an expression. For example, counting seismic events per day only needs the date part of the timestamp:

SELECT substr(time, 1, 10) AS day, COUNT(*) AS n
FROM quakes
GROUP BY day
ORDER BY n DESC
LIMIT 5;

Output (real run against the practice database):

dayn
2026-10-24158
2026-10-09136
2026-10-28105
2026-10-13101
2026-10-1998
5 rows

The five busiest UTC days are 2026-10-24 (158), 2026-10-09 (136), 2026-10-28 (105), 2026-10-13 (101) and 2026-10-19 (98). The times are in UTC, so a "day" here is a UTC day, not a local one. That's worth a footnote in any chart built from this query.

A short checklist

Practice it

Try Bucket magnitudes into bands, Busy networks, Collapse drive labels into groups, Automatic or manual? and Same car, many rows in the practice section.

Check your understanding

Six questions on GROUP BY, CASE and HAVING, using the quakes and vehicles tables. Pick an answer to get instant feedback.

0 of 6 answered

  • Correct 0
  • Incorrect 0
  • Accuracy —
1. What does SELECT mag_type, COUNT(*) FROM quakes GROUP BY mag_type return?
2. With the guide's band CASE (WHEN mag < 4 first, then WHEN mag < 5, then WHEN mag < 6, then ELSE), which band does a magnitude of 4.7 get?
3. An analyst writes CASE WHEN mag < 6 THEN 'Moderate' WHEN mag < 4 THEN 'Minor' ELSE 'Strong' END. How is an event with magnitude 3.2 labeled?
4. You want only the networks with more than 100 events (us has 1,997, ak 352, pr 95). Which query does that?
5. A CASE has WHEN mag < 4 THEN 'minor', WHEN mag < 5 THEN 'light', WHEN mag < 6 THEN 'moderate' and ELSE 'strong'. A row has mag set to NULL. What label does it get?
6. In 2024, Chevrolet Silverado 4WD appears 9 times in vehicles. Why shouldn't you treat make and model as a unique key in a join?

Build a drivetrain report

A manager wants the distribution of drivetrains in the vehicles table. Write one query that standardizes the six drive labels into three groups (AWD/4WD, FWD, RWD), counts the records in each group, and sorts from largest to smallest. Bonus tip (not graded): add a percent-of-total column to see 47.6, 26.3 and 26.1.

Tip: Ctrl+Enter (⌘+Enter on Mac) checks your answer. Everything runs in your browser.

Open in the playground