SQL HAVING Clause
The SQL HAVING clause is used to filter groups of rows returned by a GROUP BY clause based on a specified condition. It is similar to the WHERE clause but is used for aggregate functions and filtering groups of rows rather than individual rows.
Here’s a basic rundown of how HAVING works:
GROUP BY Clause: Groups rows that have the same values into summary rows.
HAVING Clause: Filters the results of the GROUP BY based on aggregate functions.
Syntax
SELECT column1, column2, aggregate_function(column)
FROM table
GROUP BY column1, column2
HAVING aggregate_function(column) condition;
Example
Consider a table Sales with the following columns:
SaleID (unique identifier for each sale)
ProductID (ID of the product sold)
Amount (amount of sale)
Table: Sales
| SaleID |
ProductID |
Amount |
| 1 |
101 |
200 |
| 2 |
101 |
150 |
| 3 |
102 |
300 |
| 4 |
102 |
350 |
| 5 |
103 |
100 |
Query
To find products with total sales greater than 400, you would use:
SELECT ProductID, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY ProductID
HAVING SUM(Amount) > 400;
Explanation
GROUP BY ProductID: Groups the sales by product.
SUM(Amount): Calculates the total sales amount for each product.
HAVING SUM(Amount) > 400: Filters out the products where the total sales are not greater than 400.
Output
| ProductID |
TotalSales |
| 102 |
650 |
In this case, ProductID 102 is the only product where the total sales exceed 400.
Notes
HAVING is used after GROUP BY and is ideal for conditions involving aggregates.
- The
WHERE clause cannot be used with aggregate functions and should be used before GROUP BY to filter individual rows.
If you have any specific scenarios or need more detailed examples, feel free to ask!