GROUP BY and aggregates: totals that hold up
Instead of reading 240 rows, summarise them — revenue by channel, orders per region. GROUP BY sets the unit of that summary and the aggregate functions compute it.
GROUP BY collapses rows
The columns after GROUP BY define groups: rows sharing a value become one line. SELECT may then contain only the grouping columns and aggregates. Listing a non-grouped column makes SQLite pick an arbitrary row's value, so the result depends on luck.
You can group by several columns. GROUP BY channel, category produces one row per combination, which quickly becomes unreadable; start with one column and add only when needed.
SELECT channel, COUNT(*) AS orders, SUM(revenue) AS revenue
FROM orders
GROUP BY channel
ORDER BY revenue DESC;
What the aggregates actually count
COUNT(*) counts rows; COUNT(col) counts rows where col is not NULL. That difference is the first step in measuring missing data. SUM and AVG skip NULLs, and return NULL when every value is NULL. For AVG, the denominator is the number of non-NULL values, not the number of rows.
MIN and MAX work on text as well as numbers, comparing lexicographically, and ROUND keeps the output readable.
| Function | Meaning | NULL handling |
|---|---|---|
| COUNT(*) | number of rows | counts NULLs |
| COUNT(col) | rows with a value | skips NULL |
| SUM(col) | total | skips NULL |
| AVG(col) | mean | skips NULL, denominator is value count |
| MIN / MAX | smallest / largest | ignores NULL |
HAVING filters groups
WHERE filters rows before grouping; HAVING filters groups after aggregation. Use HAVING for conditions on the summary, such as channels with at least ten orders. Together, WHERE reduces the work and HAVING trims the report.
SELECT channel, COUNT(*) AS orders, ROUND(AVG(revenue), 0) AS avg_rev
FROM orders
WHERE status = 'completed'
GROUP BY channel
HAVING COUNT(*) >= 10
ORDER BY orders DESC;
Cross-check the total
Add the group totals and compare with the overall total. A difference means a filter, a NULL rule or a join that multiplied rows. SUM after a LEFT JOIN is the classic case: unmatched rows can be counted twice.
A worked cross-check
After totalling revenue by channel, query the overall total without a filter and compare. They should match. A difference means a filter applied unevenly, a join that multiplied rows, or NULLs in the measure.
Make that comparison a habit and errors surface before a number is quoted. When the totals disagree, pick one group, list its source rows and compare them by hand.
Questions
Can SUM run without GROUP BY?
Yes. A bare aggregate treats the whole table as one group, so SELECT SUM(revenue) FROM orders returns a single total.
How do I get the top three per group?
Not with GROUP BY. Use the window function ROW_NUMBER with PARTITION BY, or rank rows inside each group.
Sources
Every query in this guide runs against the built-in sample data.
Open the lab