Home / SQL Tutorial / Day 7
Day 7 — GROUP BY
This is the single most useful thing in SQL for reporting. Every "sales by region" report you have ever seen is a GROUP BY.
What it does
GROUP BY collapses rows that share a value into one row, then runs your aggregate on each bunch.
SELECT group_column, AGGREGATE(other_column)
FROM table
GROUP BY group_column;
Orders per sales rep
Revenue per sales rep, biggest first
Several numbers at once
This one query is a complete rep-performance report.
Grouping by two columns
You get one row per combination — the same shape as an Excel PivotTable with two row fields.
WHERE before grouping
WHERE filters the raw rows, and then the survivors get grouped.
The rule to remember
Every column in your SELECT must either be in the GROUP BY, or be wrapped in an aggregate. There is no third option. Once that clicks, GROUP BY stops being confusing.
Try these yourself
- Count customers per City.
- Total salary per Department.
- Count orders per Status.
- Average salary per Department, rounded.
- Revenue per SalesRep for Delivered orders only, highest first.
Want this taught properly?
This tutorial covers the basics. Our SQL course in Noida takes you through window functions, CTEs and stored procedures on a real database, with projects and mentor support.
See the SQL course →