
SQL Programming
May 14, 2025 at 01:56 PM
Now that you know how to use aggregate functions like SUM(), AVG(), etc., let’s talk about how to use them per category, per product, or per customer using *GROUP BY*.
*Why GROUP BY?*
Use GROUP BY when you want to aggregate data separately for each value in a column.
*Example: Total Sales per Product*
SELECT product, SUM(quantity_sold) AS total_quantity
FROM sales
GROUP BY product;
This query shows how many units of each product were sold.
Without GROUP BY, you'd only get one total for all products combined.
*Another Example: Revenue per Region*
SELECT region, SUM(price * quantity_sold) AS revenue
FROM sales
GROUP BY region;
Useful for business insights like which region brings the most revenue.
*Golden Rule:*
- Every column in the SELECT clause (that’s not inside an aggregate function) must be in the GROUP BY.
So this is valid: 👇
SELECT customer_id, COUNT(*)
FROM orders
GROUP BY customer_id;
But this will throw an error: 👇
SELECT customer_id, COUNT(*), status
FROM orders
GROUP BY customer_id;
-- ❌ 'status' is not aggregated or grouped
*React with ❤️ if you're ready for the next quiz.* 📝
SQL Learning Series: https://whatsapp.com/channel/0029VanC5rODzgT6TiTGoa1v/1075
❤️
👍
❤
😂
😢
♥
🇮🇱
🇵🇸
🍠
🎂
99