The GROUP BY and HAVING clauses in SQL are used together to group rows based on common values in specified columns and then filter those groups. While the GROUP BY clause groups the data, the HAVING clause applies a condition to the grouped results, similar to how the WHERE clause works for individual rows.
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING aggregate_function(column2) condition;
Let’s say you have a Sales table:
SaleID | ProductID | SaleDate | Quantity | TotalAmount |
---|---|---|---|---|
1 | 101 | 2023-01-10 | 5 | 500 |
2 | 101 | 2023-02-15 | 10 | 1000 |
3 | 102 | 2023-01-20 | 3 | 450 |
4 | 103 | 2023-03-10 | 8 | 800 |
5 | 101 | 2023-04-05 | 2 | 200 |
SELECT ProductID, COUNT(SaleID) AS SaleCount
FROM Sales
GROUP BY ProductID;
ProductID | SaleCount |
---|---|
101 | 3 |
102 | 1 |
103 | 1 |
This groups the sales by ProductID and counts how many sales each product had. Now, let’s say you only want to return products that have more than one sale. This is where the HAVING clause comes in.
SELECT ProductID, COUNT(SaleID) AS SaleCount
FROM Sales
GROUP BY ProductID
HAVING COUNT(SaleID) > 1;
ProductID | SaleCount |
---|
101 | 3 |
This query groups the sales by ProductID and counts the number of sales per product. The HAVING clause filters out products that have only 1 sale, showing only products with more than 1 sale.