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_type | n |
|---|---|
| mb | 1538 |
| ml | 793 |
| mww | 141 |
| md | 122 |
| mwr | 27 |
| mb_lg | 4 |
| mw | 2 |
| ms_vx | 1 |
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):
| band | n |
|---|---|
| minor (2.5-3.9) | 939 |
| light (4.0-4.9) | 1463 |
| moderate (5.0-5.9) | 205 |
| strong (6.0+) | 21 |
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):
| drive | n |
|---|---|
| All-Wheel Drive | 6964 |
| Rear-Wheel Drive | 5824 |
| Front-Wheel Drive | 5765 |
| 4-Wheel Drive | 2796 |
| Part-time 4-Wheel Drive | 761 |
| 4-Wheel or All-Wheel Drive | 1 |
"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_group | n |
|---|---|
| AWD/4WD | 10522 |
| RWD | 5824 |
| FWD | 5765 |
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):
| net | n |
|---|---|
| us | 1997 |
| ak | 352 |
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):
| make | model | n |
|---|---|---|
| Chevrolet | Silverado 4WD | 9 |
| Chevrolet | Silverado Mud Terrain Tires 4WD | 9 |
| GMC | Sierra 4WD | 8 |
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):
| band | n | pct |
|---|---|---|
| minor (2.5-3.9) | 939 | 35.7 |
| light (4.0-4.9) | 1463 | 55.7 |
| moderate (5.0-5.9) | 205 | 7.8 |
| strong (6.0+) | 21 | 0.8 |
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):
| day | n |
|---|---|
| 2026-10-24 | 158 |
| 2026-10-09 | 136 |
| 2026-10-28 | 105 |
| 2026-10-13 | 101 |
| 2026-10-19 | 98 |
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
- As a reliable habit, every selected column is either in the
GROUP BYor wrapped in an aggregate. Some databases, SQLite included, allow non-grouped columns and return a value from an arbitrary row, which can mislead. CASEbranches run top to bottom. Put the narrowest or highest-priority rule first.- Always add an
ELSE, and check whether anything lands in it. - Use
WHEREfor row filters andHAVINGfor group filters. - Sort categories in a meaningful order, not just alphabetically.
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.