How to Filter Grouped Results in SQL Using the HAVING Clause
Last updated 8 months, 2 weeks ago | 250 views 75 5
When working with SQL, you might need to filter grouped results after performing a COUNT() operation. The HAVING clause is essential for this task, as it allows filtering after grouping the data.
✅ SQL Query to Filter Grouped Results
SELECT JobTitle, COUNT(JobTitle) AS QTY
FROM employees
GROUP BY JobTitle
HAVING QTY != 1;
Explanation
-
GROUP BY JobTitle: Groups rows by theJobTitlecolumn. -
COUNT(JobTitle) AS QTY: Counts the occurrences of each job title and assigns it an aliasQTY. -
HAVING QTY != 1: Filters out groups where the count is exactly 1.
✅ Sample Output
| JobTitle | QTY |
|---|---|
| Developer | 2 |
| Manager | 2 |
✅ Why Use HAVING Instead of WHERE?
-
The
WHEREclause filters rows before grouping. -
The
HAVINGclause filters the aggregated results after grouping.
By leveraging the HAVING clause, you can efficiently filter grouped data based on aggregated values like COUNT(), SUM(), or AVG().