SQL GROUP BY: totals per group
GROUP BY splits the table into groups and runs the aggregate once per group.
SQL skills · Summaries
What you will learn
Totals per region, signups per channel, tickets per agent: GROUP BY is how every summary table is made.
The one rule: every column in SELECT is either in GROUP BY or inside an aggregate.
The basics
GROUP BY splits the rows into groups, one per value of the column, and runs each aggregate once per group.
SELECT region, COUNT(*), SUM(amount) AS total
FROM invoices
GROUP BY region
ORDER BY total DESCThe one rule
Every column in SELECT must either be in GROUP BY or sit inside an aggregate. A column with many values per group, like the customer name when you group by region, has no single value to show, so most databases refuse the query.
Several columns
GROUP BY region, status makes one group per combination. The groups come out in no particular order; add ORDER BY when the order matters.
Worked examples
Example 1
Total invoice amount per region, largest first.
SELECT region, SUM(amount) AS total
FROM invoices
GROUP BY region
ORDER BY total DESCOne row per region.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Selecting a column that is neither grouped nor aggregated, such as the customer name when you group by region.
- Forgetting GROUP BY and getting one total for the whole table.
- Expecting the groups to come out sorted without ORDER BY.
Where you will use it at work
- Marketing: spend per channel.
- HR: headcount per department.
- Operations: units shipped per warehouse.
Questions people ask
Can I group by two columns?
Yes. GROUP BY region, status makes one row per combination.
Can I use the alias in GROUP BY?
In PostgreSQL, MySQL, SQLite and Snowflake, yes. In SQL Server and Oracle, repeat the expression.
Why is my count too high after a join?
Joins repeat rows. Count a unique ID, or use COUNT(DISTINCT id).
Ready to write it yourself?
Practice GROUP BY