SQL reference

SQL GROUP BY: totals per category

In Excel, you'd reach for
fxA pivot table: field in Rows, SUM or COUNT in Values

GROUP BY collapses rows that share a value into one row per value, then lets you total each group with SUM, COUNT, AVG, MIN or MAX. It's an Excel pivot table in one line.

The rule that trips everyone up: every column in SELECT must either be in the GROUP BY or be inside a total. Otherwise the database doesn't know which row's value to show.

SQL GROUP BY explained as an Excel pivot table: orders grouped by region and summed
GROUP BY is a pivot table: rows land in buckets, then each bucket is totalled. Download · Save to Pinterest

Syntax

SELECT category_col, SUM(number_col)
FROM table
GROUP BY category_col;
Try itEdit the query, then Run
monthregionordersunits
2026-01Asia Pacific30102
2026-01Europe2365
2026-01Latin America2472
2026-01North America2474
2026-02Asia Pacific2574
2026-02Europe1449
2026-02Latin America2776
2026-02North America2790
2026-03Asia Pacific2585
2026-03Europe2473

Showing 10 of 12 rows. Press Run to see them all.

Grouping by two columns gives one row per combination, like dragging two fields into Rows. To filter on the totals afterwards (only regions above 100 units), see HAVING vs WHERE. Want the months as columns instead of rows? That's a pivot.

Your turn

How many tickets did each agent handle, per priority? Columns agent, priority, tickets.

This page on one card

SQL GROUP BY: totals per category: the Excel way (A pivot table: field in Rows) and the SQL query, side by side
SQL GROUP BY: totals per category, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows