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 BYClause: Groups rows that have the same values into summary rows.HAVINGClause: Filters the results of theGROUP BYbased 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
HAVINGis used afterGROUP BYand is ideal for conditions involving aggregates.- The
WHEREclause cannot be used with aggregate functions and should be used beforeGROUP BYto filter individual rows.
If you have any specific scenarios or need more detailed examples, feel free to ask!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
