Aggregations

The Power of Grouping: GROUP BY

Senior Data Analyst
January 18, 2026
6 min read

The Segmented Question

The numbers from yesterday were great, but my manager wanted more. *"Okay, total revenue is good, but what's the breakdown BY COUNTRY?"*

A single total is useful. A breakdown BY category is insightful. This is the core of business intelligence.

The Quest: The Bucketing Logic

The `GROUP BY` clause tells SQL to "Split" the data into buckets first, and THEN run the aggregation on each bucket separately.

The Implementation: One Query, Many Answers

-- Revenue broken down by country

SELECT

country,

SUM(order_amount) AS country_revenue

FROM orders

GROUP BY country;

How It Works

1. SQL scans all the orders.

2. It creates a "Virtual Bucket" for each unique `country` value.

3. It calculates `SUM(order_amount)` for each bucket independently.

4. It returns one row per bucket.

Multiple Groupings

You can group by more than one column!

-- Revenue by country, then by product category

SELECT

country,

category,

SUM(order_amount) AS segment_revenue

FROM orders

GROUP BY country, category;

The "Oops" Moment

My first time using `GROUP BY`, I tried to select a column that wasn't in the grouping:

`SELECT country, product_name, SUM(amount) FROM orders GROUP BY country;`

SQL threw an error.

**Pro Tip**: Every column in your `SELECT` list MUST either be in the `GROUP BY` clause OR wrapped in an aggregation function like `SUM()` or `COUNT()`. You cannot ask for a single `product_name` if there are 1000 products in that country.

The Victory

The manager got a table with "Germany: $1.2M, UK: $800K, USA: $3M..." He could now compare regional performance at a glance. I had learned to create the "Executive Dashboard" without any fancy BI tools.

Your Task for Today

Use `GROUP BY` on a category column (like `status`, `region`, or `department`). Count the rows in each group.

*Day 19: Filtering Groups—HAVING vs. WHERE.*

Ready to put your knowledge into practice?

Join SQL Mastery and learn through interactive exercises.