🏆 OSM

SQL Aggregation and Grouping for Beginners: COUNT, SUM, AVG, GROUP BY, and HAVING Explained

2 weeks ago
2025-09-04 11:45:13

Aggregation and Grouping

Summarizing Your Data: A First Look at Aggregate Functions

Aggregate functions summarize many rows into one result.
The most common are:

Example: Sales table

+----+----------+---------+
| ID | Product  | Amount  |
+----+----------+---------+
| 1  | Laptop   | 1000    |
| 2  | Phone    | 500     |
| 3  | Laptop   | 800     |
| 4  | Phone    | 600     |
+----+----------+---------+

Query – total sales amount:

SELECT SUM(Amount) AS TotalSales
FROM Sales;

Result:

+------------+
| TotalSales |
+------------+
| 2900       |
+------------+

From Raw Data to Real Insight: Mastering GROUP BY

GROUP BY lets you group rows that share the same value.
For example: total sales by product.

SELECT Product, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Product;

Result:

+---------+------------+
| Product | TotalSales |
+---------+------------+
| Laptop  | 1800       |
| Phone   | 1100       |
+---------+------------+

Filtering Groups: The Difference Between WHERE and HAVING

Example: Show products with sales greater than 1500.

SELECT Product, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Product
HAVING SUM(Amount) > 1500;

Result:

+---------+------------+
| Product | TotalSales |
+---------+------------+
| Laptop  | 1800       |
+---------+------------+

How to Count Smarter with COUNT and DISTINCT

Sometimes you want to count unique values, not just rows.

SELECT COUNT(DISTINCT Product) AS UniqueProducts
FROM Sales;

Result:

+----------------+
| UniqueProducts |
+----------------+
| 2              |
+----------------+

This tells us there are 2 unique product types.


✅ Pro Tip

When working with GROUP BY, always make sure that every column in your SELECT (except aggregates like SUM, COUNT, AVG) is also listed in your GROUP BY. Otherwise, your query may fail or give incorrect results.

Previous Blog

SQL Data Manipulation and Definition Basics: INSERT, UPDATE, DELETE, CREATE TABLE, and Keys Explained

Next Blog

Practical SQL for Beginners: Projects, Commands, and Common Mistakes Explained

© 2025 Oscar Myo Min

Design by Kai

𝕏 GitHub