SQL HAVING
HAVING is used to filter records after the GROUP BY clause based on aggregate conditions.
HAVING clause is used to filter grouped data after applying aggregate functions like COUNT(), SUM(), AVG(), MIN(), or MAX().
Basic Syntax
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name HAVING condition;
Example: Using HAVING with COUNT(),Find customers who placed more than 1 order.
SELECT CustomerID, COUNT(OrderID) AS TotalOrders FROM Orders GROUP BY CustomerID HAVING COUNT(OrderID) > 1;
Example: Using HAVING with SUM(), Find customers whose total purchase amount is greater than 20000.
SELECT CustomerID, SUM(Price) AS TotalAmount FROM Orders GROUP BY CustomerID HAVING SUM(Price) > 20000;
Example Using WHERE and HAVING Together
SELECT CustomerID, SUM(Price) AS TotalAmount FROM Orders WHERE Price > 1000 GROUP BY CustomerID HAVING SUM(Price) > 20000; Explanation: WHERE filters rows first (Price > 1000) GROUP BY groups by CustomerID HAVING filters groups (SUM(Price) > 20000)
Execution Order in SQL
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
Exam/Interview Definition:
HAVING in SQL Server is used to filter grouped records after applying aggregate functions, usually together with the GROUP BY clause.