HAVING Clause

SQL AggregationGroupingFree Lesson

Advertisement

The HAVING Clause

The HAVING clause filters groups created by GROUP BY — like WHERE, but for aggregated data.

💡 HAVING is used after GROUP BY to filter groups based on aggregate conditions.

Basic Syntax

SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING aggregate_condition;

Example

SELECT department, COUNT(*) AS employee_count, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
WHERE hire_date >= '2020-01-01'
GROUP BY department
HAVING COUNT(*) > 1
ORDER BY avg_salary DESC;

WHERE vs HAVING

ClauseFiltersWhenCan Use Aggregates
WHEREIndividual rowsBefore GROUP BYNo
HAVINGGroupsAfter GROUP BYYes

✏️ Exercise: Write a query that uses HAVING to find departments with more than 2 employees

See Solution


SELECT department, COUNT(*) AS count
FROM employees
GROUP BY department
HAVING COUNT(*) > 2
ORDER BY count DESC;

✅ Key Takeaways

  1. HAVING filters groups after aggregation
  2. Use with aggregate functions like COUNT, SUM, AVG, MIN, MAX
  3. WHERE filters individual rows BEFORE grouping
  4. HAVING filters groups AFTER grouping
  5. ORDER BY comes last after GROUP BY and HAVING

Advertisement

Need Expert SQL Help?

Get personalized SQL training or database consulting.

Advertisement