T
Tech Town
Log InSign Up Free
← Back to Blog

June 17, 2025 · admin

GROUP BY

๐Ÿ“Š SQL GROUP BY โ€“ Group and Aggregate Your Data Effectively

The SQL GROUP BY clause is used to organize data into groups and apply aggregate functions like SUM(), 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 rows
  • SUM() โ€“ Calculate the total
  • AVG() โ€“ Get the average
  • MAX() / 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 by
  • aggregate_function: Operation performed on each group

โœ… Example: Sales by Region

Imagine a sales table:

regionamount
East100
West200
East150
North120

Query:

SELECT region, SUM(amount) AS total_sales
FROM sales
GROUP BY region;

๐Ÿงพ Result:

regiontotal_sales
East250
West200
North120

๐ŸŽฏ 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

TipDescription
๐ŸŽฏ Use aliases (AS)For cleaner column names in results
๐Ÿ“ Keep SELECT and GROUP BY in syncAll non-aggregated columns in SELECT must be in GROUP BY
โšก Filter earlyUse WHERE before GROUP BY to improve performance
๐Ÿšง Use HAVING to filter groupsDonโ€™t use WHERE with aggregates โ€“ use HAVING instead

๐Ÿšฆ GROUP BY vs HAVING vs WHERE

ClausePurposeUsed With Aggregates?
WHEREFilters rows before groupingโŒ
GROUP BYGroups rowsโœ… (required)
HAVINGFilters 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 BY organizes 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(), and COUNT()
  • Use HAVING to filter grouped results