SQL Grouping & Filtering β GROUP BY and HAVING Explained
Introduction β Why Learn SQL Grouping & Filtering?
When analyzing large datasets, it’s often essential to group similar records and apply filters on aggregated data. SQL provides two powerful clauses to do this:
GROUP BY: Groups rows sharing a common valueHAVING: Filters the results after aggregation
Mastering these clauses allows you to:
- Aggregate metrics like COUNT, SUM, AVG
- Organize data into meaningful categories
- Apply filters to grouped results (unlike WHERE)
In this tutorial, youβll learn how to:
- Group data using
GROUP BY - Filter grouped data using
HAVING - Combine both for powerful reporting queries
Topics Covered
| Topic | Description |
|---|---|
| SQL GROUP BY | Organize results into categories for aggregation |
| SQL HAVING | Apply conditions on grouped and aggregated data |
SQL GROUP BY β Categorize and Aggregate Data
The GROUP BY clause is used to group rows based on one or more columns. Itβs commonly used with aggregate functions like SUM(), AVG(), COUNT(), etc.
Syntax:
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1;
Example β Total Salary by Department:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
This groups employees by department and calculates the total salary per group.
SQL HAVING β Filter Aggregated Results
The HAVING clause works like WHERE, but it applies after the GROUP BY has aggregated data.
Syntax:
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Example β Departments with Total Salary > 100,000:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;
This filters out departments where the total salary is β€ 100,000.
GROUP BY vs HAVING vs WHERE β Key Differences
| Clause | Use Case | Applies To |
|---|---|---|
WHERE | Filters before aggregation | Individual rows |
GROUP BY | Groups rows based on column values | Raw rows |
HAVING | Filters after aggregation | Grouped data |
Example β GROUP BY + HAVING in Action
SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) >= 5;
This query:
- Filters out inactive employees
- Groups active employees by department
- Returns only departments with 5 or more active employees
Best Practices for GROUP BY and HAVING
| Best Practices | Common Mistakes |
|---|---|
Always use aggregate functions with HAVING | Donβt use HAVING like WHERE for raw data |
Use AS to label your result columns | Avoid ambiguous or default column names |
Use WHERE for row-level filtering | Donβt skip GROUP BY when aggregating multiple groups |
| Ensure grouped column is in SELECT | Avoid syntax errors by mismatching grouped and selected columns |
Summary β Recap & Next Steps
SQLβs GROUP BY and HAVING clauses let you analyze, categorize, and filter data with precision. They are fundamental for data analysis, reporting, and summarizing datasets.
Key Takeaways:
- Use
GROUP BYto organize data for aggregation - Use
HAVINGto filter groups after aggregation - Combine with aggregate functions for insights like totals, averages, and counts
Real-World Relevance:
These clauses are widely used in analytics dashboards, financial reports, performance metrics, and customer segmentation queries.
Next Up: Explore SQL Subqueries & Nested Queries to build more dynamic and layered logic.
FAQs β SQL Grouping & Filtering
Can I use HAVING without GROUP BY?
Technically yes, but it’s only meaningful when you’re using aggregate functions. Otherwise, use WHERE.
Whatβs the difference between WHERE and HAVING?
WHERE filters before grouping; HAVING filters after aggregation.
Can I group by multiple columns?
Yes, just separate them with commas:
GROUP BY department, location;
Can I use aliases in HAVING?
Not in all databases. Itβs safer to repeat the aggregate expression in HAVING.
What aggregate functions can be used with GROUP BY?
COUNT(), SUM(), AVG(), MIN(), MAX(), and even nested functions like ROUND(AVG(salary), 2).
Share Now :
