Memra

GROUP BY: per-category summaries

◈ 2 cards

One summary row per group.

Summarize per group

GROUP BY splits rows into groups and runs the aggregate once per group. "How many books per genre?":

SELECT genre, COUNT(*) AS books
FROM books
GROUP BY genre;

The rule: every column in the SELECT must either be in the GROUP BY or wrapped in an aggregate. (Postgres will tell you off otherwise.) You can group by several columns to get one row per combination.

books10 rowsfiction3science2poetry2history2children1
GROUP BY partitions the rows, then runs the aggregate once inside each part. That is the whole reason every selected column must be grouped or aggregated — anything else has no single value to show per group.
NORMAL ~/memra/learn/postgresql/group-by utf-8 LF