Consider a table Orders with columns CustomerID and OrderID. What is the output of this query?
SELECT CustomerID, COUNT(OrderID) AS OrderCount FROM Orders GROUP BY CustomerID HAVING COUNT(OrderID) > 2;
Assume the table has these rows:
CustomerID | OrderID -----------|-------- 1 | 101 1 | 102 2 | 103 2 | 104 2 | 105 3 | 106
SELECT CustomerID, COUNT(OrderID) AS OrderCount FROM Orders GROUP BY CustomerID HAVING COUNT(OrderID) > 2;
Remember, HAVING filters groups after aggregation.
The query groups orders by CustomerID and counts orders per customer. HAVING filters groups with count > 2. Only CustomerID 2 has 3 orders, so only that row appears.
What is the main purpose of the HAVING clause in SQL?
Think about when filtering happens in relation to grouping.
HAVING filters groups after aggregation, unlike WHERE which filters rows before grouping.
Which option contains a syntax error in using the HAVING clause?
SELECT Department, AVG(Salary) AS AvgSalary FROM Employees GROUP BY Department HAVING Salary > 50000;
Remember what HAVING can filter on after grouping.
HAVING cannot filter on a column directly unless it is part of GROUP BY or an aggregate function. 'Salary' alone is invalid here.
Given a large Sales table with columns Region, Amount, and SaleDate, which query is more efficient to find regions with total sales over 10000 in 2023?
Filter rows before grouping when possible.
Filtering rows with WHERE before grouping reduces data processed in aggregation, improving efficiency.
Given the table Products with columns Category and Price, why does this query return no rows?
SELECT Category, AVG(Price) AS AvgPrice FROM Products GROUP BY Category HAVING AVG(Price) < 0;
Think about the possible values of average price.
Average price cannot be negative if prices are non-negative, so the HAVING condition filters out all groups.