SQL Server में HAVING Clause क्या है?
🧠 Definition (Memory के लिए)
SQL Server में HAVING clause का उपयोग GROUP BY के साथ aggregate functions पर filtering करने के लिए किया जाता है। WHERE clause individual rows filter करता है, जबकि HAVING clause grouped rows पर condition apply करता है।
🧩 Syntax
SELECT column_name, AGG_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING AGG_FUNCTION(column_name) condition;
🧪 Example
CREATE TABLE Sales (
ID INT PRIMARY KEY,
Product NVARCHAR(50),
Amount INT
);
INSERT INTO Sales VALUES
(1,'Pen', 50),
(2,'Pen', 30),
(3,'Book', 200),
(4,'Book', 150),
(5,'Pen', 40);
-- Product का total sales 100 से ज्यादा वाले products select करें
SELECT Product, SUM(Amount) AS TotalAmount
FROM Sales
GROUP BY Product
HAVING SUM(Amount) > 100;
📤 Output
Product | TotalAmount
---------------------
Pen | 120
Book | 350
💡 Explanation
- GROUP BY clause Product के आधार पर rows को group करता है।
- SUM(Amount) हर group का total calculate करता है।
- HAVING SUM(Amount) > 100 filter करता है कि केवल वो groups show हों जिनका total 100 से ज्यादा है।
🎯 Interview Questions & Answers
- Q: HAVING clause का उपयोग क्यों किया जाता है?
A: GROUP BY के साथ aggregate function के result पर filtering करने के लिए। - Q: WHERE और HAVING में अंतर क्या है?
A: WHERE individual rows filter करता है, HAVING grouped rows को filter करता है। - Q: HAVING clause के बिना भी GROUP BY possible है?
A: हाँ, GROUP BY बिना HAVING के aggregate result दिखा सकता है। HAVING optional है।
📘 Conclusion
✅ SQL Server में HAVING clause grouped rows के लिए aggregate filtering के लिए essential है। यह WHERE clause की limitation को दूर करता है और complex reports में बहुत useful होता है। हमेशा aggregate functions के साथ grouping और filtering logic को ध्यान में रखें।

0 Comments