(because sometimes you want to calculate things on grouped data, not individual rows)
🔧 Quick Syntax
SELECT column, aggregate_function(column)
FROM table
GROUP BY column;
This tells SQL:
“Group the rows by a column, and apply aggregate functions (like SUM, AVG, COUNT) on the grouped data.”
👀 Imagine You Have This Table:
🧑 sales
table:
sale_id | product | quantity | sale_date |
---|---|---|---|
1 | Laptop | 3 | 2024-01-01 |
2 | Phone | 5 | 2024-01-01 |
3 | Laptop | 2 | 2024-01-02 |
4 | Phone | 3 | 2024-01-02 |
5 | Laptop | 4 | 2024-01-03 |
6 | Phone | 7 | 2024-01-03 |
Scenario: You want to calculate the total quantity sold for each product.
Step 1: GROUP BY Product
Here, we’ll group by the product to calculate the total quantity sold for each one.
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;
✅ Result:
product | total_quantity |
---|---|
Laptop | 9 |
Phone | 15 |
🧃 Recap
GROUP BY
groups the data by a column (in this case,product
).- We use aggregate functions like
SUM
,AVG
,COUNT
on the grouped data. - The result shows total quantities sold for each product.