Junior
What is the purpose of the HAVING operator in SQL?
sobes.tech AI
Answer from AI
The HAVING operator in SQL is used to filter groups of rows created by the GROUP BY operator. Unlike WHERE, which filters individual rows before grouping, HAVING applies to the aggregated results of groups after they are created.
Main use cases:
- Filtering groups based on aggregated values (for example, selecting only groups with a total income of more than 1000).
- Filtering groups where the number of elements meets a certain condition (for example, selecting groups containing more than 5 orders).
Example of a query structure with USING:
-- Select the department where the total salary exceeds 100,000
SELECT
department,
SUM(salary) AS total_salary
FROM
employees
GROUP BY
department
HAVING
SUM(salary) > 100000;