SQL
Aggregate Data with GROUP BY and HAVING Clauses
Discover how to group rows with `GROUP BY` and filter those groups using `HAVING` in SQL, perfect for generating summary reports and analytics.
SELECT category, COUNT(id) AS total_products, AVG(price) AS average_price
FROM products
GROUP BY category
HAVING COUNT(id) > 5 AND AVG(price) > 50.00;
How it works: This query groups products by their `category`, calculating the total number of products and their average price for each category. The `HAVING` clause then filters these groups, showing only categories that have more than 5 products and an average price greater than 50.00. `GROUP BY` is used for aggregating data, and `HAVING` filters the results of aggregate functions, unlike `WHERE` which filters individual rows before aggregation.