Sobes.tech
Junior

What is the HAVING operator and what is it used for in SQL?

sobes.tech AI

Answer from AI

The HAVING operator is used in SQL to filter groups created with the GROUP BY clause. It is similar to the WHERE operator but applies to aggregated results (such as the results of COUNT, SUM, AVG functions) after grouping, rather than to individual rows of the original table.

It is used for:

  • Filtering groups based on conditions involving aggregate functions.
  • Selecting groups that meet certain criteria.

For example, to find departments with more than 10 employees:

SELECT department, COUNT(*) // Select the department name and the number of employees
FROM employees // Retrieve data from the employees table
GROUP BY department // Group by department name
HAVING COUNT(*) > 10; // Filter groups to only those with more than 10 employees