Junior — Middle
How does the HAVING operator work in SQL and what is it used for in queries?
sobes.tech AI
Answer from AI
The HAVING operator in SQL is used to filter results after grouping data with GROUP BY. Unlike WHERE, which filters rows before grouping, HAVING filters already grouped data.
For example, if you want to select groups with a total sales amount greater than a certain value:
SELECT department, SUM(sales) AS total_sales
FROM sales_data
GROUP BY department
HAVING SUM(sales) > 10000;
Here, HAVING filters only those departments where the total sales exceed 10,000.