📊 SQL GROUP BY – Group and Aggregate Your Data Effectively
The SQL
GROUP BYclause is used to organize data into groups and apply aggregate functions likeSUM(),COUNT(),AVG(), etc., on each group.
Whether you’re summarizing sales, counting customers, or calculating averages, GROUP BY is a must-know tool for working with relational data.
📘 What is SQL GROUP BY?
The GROUP BY clause groups rows that have the same values into summary rows. It’s typically used with aggregate functions such as:
COUNT()– Count the number of rowsSUM()– Calculate the totalAVG()– Get the averageMAX()/MIN()– Find highest/lowest values
🧾 Syntax of SQL GROUP BY
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
column1: The column to group byaggregate_function: Operation performed on each group
✅ Example: Sales by Region
Imagine a sales table:
| region | amount |
|---|---|
| East | 100 |
| West | 200 |
| East | 150 |
| North | 120 |
Query:
SELECT region, SUM(amount) AS total_sales
FROM sales
GROUP BY region;
🧾 Result:
| region | total_sales |
|---|---|
| East | 250 |
| West | 200 |
| North | 120 |
🎯 This summarizes sales for each region.
🎯 Use Cases for SQL GROUP BY
- 📊 Total revenue by product, region, or category
- 🧮 Count users by subscription plan
- 🗓️ Average daily traffic
- 🧾 Summarize data for dashboards and reports
💡 Multiple Columns in GROUP BY
You can group by multiple columns to create detailed summaries.
SELECT region, product, SUM(amount) AS total_sales
FROM sales
GROUP BY region, product;
🧾 Now you get sales breakdown by region and product.
⚠️ GROUP BY Best Practices
| Tip | Description |
|---|---|
| 🎯 Use aliases (AS) | For cleaner column names in results |
| 📏 Keep SELECT and GROUP BY in sync | All non-aggregated columns in SELECT must be in GROUP BY |
| ⚡ Filter early | Use WHERE before GROUP BY to improve performance |
🚧 Use HAVING to filter groups | Don’t use WHERE with aggregates – use HAVING instead |
🚦 GROUP BY vs HAVING vs WHERE
| Clause | Purpose | Used With Aggregates? |
|---|---|---|
WHERE | Filters rows before grouping | ❌ |
GROUP BY | Groups rows | ✅ (required) |
HAVING | Filters grouped results (after GROUP BY) | ✅ |
Example:
SELECT region, SUM(amount) AS total_sales
FROM sales
WHERE amount > 50
GROUP BY region
HAVING SUM(amount) > 200;
📝 Summary
GROUP BYorganizes data into groups based on one or more columns- It’s essential for summary reports and analytics
- Combine it with aggregate functions like
SUM(),AVG(), andCOUNT() - Use
HAVINGto filter grouped results

