SQL Tutorial
Estimated reading: 3 minutes 53 views

πŸ“Š 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 value
  • HAVING: 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 BYOrganize results into categories for aggregation
πŸ”Ž SQL HAVINGApply 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

ClauseUse CaseApplies To
WHEREFilters before aggregationIndividual rows
GROUP BYGroups rows based on column valuesRaw rows
HAVINGFilters after aggregationGrouped 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 HAVINGDon’t use HAVING like WHERE for raw data
Use AS to label your result columnsAvoid ambiguous or default column names
Use WHERE for row-level filteringDon’t skip GROUP BY when aggregating multiple groups
Ensure grouped column is in SELECTAvoid 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 BY to organize data for aggregation
  • Use HAVING to 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ“Š SQL Grouping & Filtering

Or Copy Link

CONTENTS
Scroll to Top