
Aggregation and Grouping
Summarizing Your Data: A First Look at Aggregate Functions
Aggregate functions summarize many rows into one result.
The most common are:
COUNT() → how many rows
SUM() → total value
AVG() → average value
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
WHERE → filters rows before grouping
HAVING → filters results after grouping
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.