The village office’s monthly tally: the register grouped by colour, COUNT/SUM/AVG on the board, HAVING striking groups. Run by a real SQLite. An interactive…
Why it matters
GROUP BY and aggregates are the backbone of SQL reports and analytics. The two confusions that always come up, "why can’t a plain column sit in SELECT with GROUP BY" and "when WHERE, when HAVING", clear up once you see the rows go into baskets and HAVING strike out whole baskets.
The key idea
HAVING filters groups after aggregation, WHERE filters rows before it
Common mistakes
A query errors with "column must appear in GROUP BY", after only adding nama One RT has many names, so a name per group is ambiguous. PostgreSQL refuses it, as does MySQL with ONLY_FULL_GROUP_BY (the default since 5.7); SQLite answers with the name from one of the rows. Put the column in GROUP BY, or wrap it in an aggregate (MAX(nama), GROUP_CONCAT(nama)).
WHERE AVG(iuran) > 15000 errors: no aggregate allowed there WHERE runs before grouping, so AVG does not exist yet (SQLite: "misuse of aggregate"). Use HAVING for a condition on an aggregate.
COUNT(column) differs from COUNT(*) on the same rowsCOUNT(*) counts every row; COUNT(column) skips NULL. SUM, AVG, MIN and MAX skip NULL too, so AVG is the average of the filled-in ones only.
Try it in this playground
Group by another column Swap GROUP BY rt for pekerjaan: the baskets change, and so do the colours.
Compare COUNT(*) with COUNT(iuran) The second skips NULL: those who have not paid are not counted.
Filter groups with HAVING Write a condition on an aggregate in HAVING: the groups that fail are struck out whole.
See where a bare column comes from Add a column that is not grouped: the row it came from lights up in the book.