Learning navigation

Code with Animation

GROUP BY

Split rows into groups and compute one aggregate per group, with the one rule PostgreSQL insists on for the SELECT list.

SQL6 min readConcept 20 of 44

One result row per group

GROUP BY puts all rows that share the same value in a column into one group. Each aggregate in the SELECT list is then computed separately inside each group, and the query returns one row per group.

Without GROUP BY, all rows form one single group. That is why SELECT count(*) FROM players returns exactly one row.

Totals per category

Real questions are rarely about the whole table: "how many players per team?", "total sales per month?", "orders per customer?". GROUP BY answers all of them with one query.

Count players per team

SELECT team, count(*) AS n, max(points) AS best
FROM players
GROUP BY team;

The 8 players fall into 3 groups: Red has 3 rows, Blue has 3 and Green has 2. The result has 3 rows, one for each team, and count(*) and max(points) are worked out inside each team.

When you group by a column that has NULL, all the NULLs go into one group. Chen and Eli both have NULL points, so GROUP BY points gives them one shared NULL group of 2 rows.

Group by team, by points, or by nothing

Watch the last column of the source table: it shows the group every row falls into. Then press Also SELECT name to see the real error.

SELECT team, count(*) AS n
FROM players
GROUP BY team;
players (8 rows)
nametextteamtextpointsintegergroup
AshaRed31Red
BenBlue17Blue
ChenRedNULLRed
DaraGreen24Green
EliBlueNULLBlue
FayRed24Red
GusGreen40Green
HanaBlue17Blue
Result (3 rows)
teamtextnbigint
Red3
Blue3
Green2

GROUP BY team puts the 8 rows into 3 groups, and the query returns one row per group. The aggregate is computed separately inside each group. Without ORDER BY the order of the rows is not promised.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1`players` has 8 rows from 3 teams. How many rows does `SELECT team, count(*) FROM players GROUP BY team` return?
  2. 2What happens with `SELECT team, name, count(*) FROM players GROUP BY team`?
  3. 3Two players have NULL `points`. How many groups do they make in `GROUP BY points`?

Remember this

  • GROUP BY makes one group per different value, and the query returns one row per group.
  • Aggregates are computed separately inside each group.
  • Every plain column in SELECT must be in GROUP BY or inside an aggregate.
  • All NULLs fall into one group, and the order of groups is not promised without ORDER BY.

Done with this concept?

Mark it complete to track your progress. No login needed.