← Lessons

quiz vs the machine

Silver1080

Databases

GROUP BY and Aggregates

Grouping collapses many rows into one summary row per distinct key.

4 min read · intro · beat Silver to climb

Turning Rows Into Summaries

An aggregate function like COUNT, SUM, AVG, MIN, or MAX reduces many values into a single number. GROUP BY tells the engine which rows belong together so each aggregate is computed once per group instead of once for the whole table.

How Grouping Works

  • The engine partitions rows by the grouping columns.
  • Each distinct combination of those columns becomes one output row.
  • Aggregates run over the rows inside each group.
  • Without GROUP BY, the whole table is treated as one big group.

The Single Group Rule

Every column in the SELECT list must either appear in GROUP BY or be wrapped in an aggregate. Otherwise the engine cannot decide which value to show for a group that has many different values. This rule catches a very common mistake where a plain column is mixed with an aggregate.

Key idea

GROUP BY splits rows into groups by key, and every selected column must be a grouping column or an aggregate over the group.

Check yourself

Answer to earn rating on the learn ladder.

1. What must be true of a non aggregated column in a grouped query?

2. What does a query with aggregates but no GROUP BY return?