📊 GROUP BY = Summarize Your Data
Need totals, averages, counts? GROUP BY aggregates data. Sales by category, users by country, orders by month.
📝 Basic GROUP BY
-- Count per category
SELECT category, COUNT(*) as product_count
FROM products
GROUP BY category;
-- Average price per category
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category;
-- Total sales per customer
SELECT customer_id, SUM(total) as total_spent
FROM orders
GROUP BY customer_id;
-- Orders per month
SELECT
DATE_TRUNC('month', order_date) as month,
COUNT(*) as order_count,
SUM(total) as total_revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month DESC;
🎯 Advanced GROUP BY
-- Multiple columns
SELECT
category,
status,
COUNT(*) as count,
AVG(price) as avg_price
FROM products
GROUP BY category, status;
-- With HAVING (filter groups)
SELECT
category,
COUNT(*) as product_count
FROM products
GROUP BY category
HAVING COUNT(*) > 5;
-- With ROLLUP (subtotals)
SELECT
category,
SUM(price) as total
FROM products
GROUP BY ROLLUP(category);
-- With CUBE (all combinations)
SELECT
category,
status,
COUNT(*) as count
FROM products
GROUP BY CUBE(category, status);
💡 Common Aggregations
- COUNT(): Number of rows
- SUM(): Sum of values
- AVG(): Average value
- MIN(): Minimum value
- MAX(): Maximum value
- COUNT(DISTINCT): Unique values
“Need sales by category. GROUP BY + SUM did it. One query, instant report. GROUP BY is essential for analytics.”

