Sobes.tech
Junior

What is the HAVING clause?

sobes.tech AI

Answer from AI

The HAVING clause is used in SQL to filter the results of groups created by the GROUP BY clause.

Differences from WHERE:

  • WHERE filters individual rows before grouping.
  • HAVING filters groups after they are created and after applying aggregate functions.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING group_condition
ORDER BY column1, column2, ...;

Example: Select departments where the average salary exceeds 50,000.

SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;