Sobes.tech
Junior

What is the HAVING operator in SQL and how is it used?

sobes.tech AI

Answer from AI

The HAVING operator in SQL is used to filter rows after data has been grouped using the GROUP BY operator. It is applied to aggregate functions.

-- Select departments where the average salary exceeds 50,000
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;

Difference between WHERE and HAVING:

  • WHERE is applied before grouping and filters individual rows.
  • HAVING is applied after grouping and filters groups of rows based on aggregate function results.
Operator Application Action
WHERE Before GROUP BY Filters individual rows
HAVING After GROUP BY Filters groups of rows