Grouping Data: GROUP BY and HAVING 🗂️
In the previous topic, we used aggregate functions to compute a single summary across an entire table (e.g., total company revenue).
Now, imagine management asks:
- "What is the total revenue per product category?"
- "What is the average salary for each department?"
- "Show me departments with more than 5 employees."
To calculate summary statistics for different categories within the same table, we use the GROUP BY clause and filter aggregated groups with HAVING.
1. How GROUP BY Works Visually 🧩
GROUP BY takes all rows in a table, slices them into separate buckets (groups) based on matching values in one or more columns, and then applies aggregate functions to each bucket independently:
Individual Rows: GROUP BY department: Aggregate Output:
┌───────────┬─────────────┬────────┐ ┌──────────────────────────┐ ┌────────────┬───────────┐
│ Name │ Department │ Salary │ │ Engineering Group: │ │ Department │ AvgSalary │
├───────────┼─────────────┼────────┤ │ - Aarav (95000) │ ─>├────────────┼───────────┤
│ Aarav │ Engineering │ 95000 │ │ - Priya (98000) │ │ Engineering│ 96500 │
│ Rahul │ Marketing │ 62000 │ ├──────────────────────────┤ ├────────────┼───────────┤
│ Priya │ Engineering │ 98000 │ │ Marketing Group: │ │ Marketing │ 63000 │
│ Amit │ Sales │ 55000 │ │ - Rahul (62000) │ ─>├────────────┼───────────┤
│ Neha │ Marketing │ 64000 │ │ - Neha (64000) │ │ Sales │ 55000 │
└───────────┴─────────────┴────────┘ ├──────────────────────────┤ └────────────┴───────────┘
│ Sales Group: │
│ - Amit (55000) │
└──────────────────────────┘
In SQL:
SELECT department, COUNT(*) AS total_staff, AVG(salary) AS avg_salaryFROM employeesGROUP BY department;2. The Golden Rule of GROUP BY ⚠️
Here is the single most common syntax error beginners face when learning SQL:
🚨 The Golden Rule:
Whenever you use
GROUP BY, every single column listed in yourSELECTclause must EITHER:
- Be included in the
GROUP BYclause, OR- Be wrapped inside an Aggregate Function (
SUM,AVG,COUNT,MIN,MAX).
Look at this broken query:
-- ❌ SYNTAX ERROR IN STANDARD SQL / POSTGRESQL:SELECT department, first_name, AVG(salary)FROM employeesGROUP BY department;Why does this fail?
Think about it from the database engine's perspective:
In the Engineering department, there are two employees: Aarav and Priya.
When the query collapses all Engineering rows into a single summary row, which first_name should it print beside the average salary? Aarav? Priya? Both?
Because this is ambiguous, the database engine rightfully rejects the query!
3. Grouping by Multiple Columns 🗃️
You can group by more than one column. This creates sub-groups within groups:
SELECT country, department, COUNT(*) AS employee_count, AVG(salary) AS avg_payFROM employeesGROUP BY country, department;Result:
┌─────────┬─────────────┬────────────────┬─────────┐
│ country │ department │ employee_count │ avg_pay │
├─────────┼─────────────┼────────────────┼─────────┤
│ India │ Engineering │ 12 │ 95000 │
│ India │ Marketing │ 5 │ 62000 │
│ USA │ Engineering │ 8 │ 125000 │
│ USA │ Marketing │ 4 │ 88000 │
└─────────┴─────────────┴────────────────┴─────────┘
4. Filtering Groups: The HAVING Clause 🎛️
What if you want to find only departments where the average salary exceeds ₹70,000?
A beginner might instinctively try to write:
-- ❌ COMPILATION ERROR: Aggregate functions not allowed in WHERE!SELECT department, AVG(salary)FROM employeesWHERE AVG(salary) > 70000GROUP BY department;Why Can't We Use Aggregate Functions in WHERE?
Remember the execution order! The WHERE clause runs before groups are created and before aggregate calculations exist.
To filter after groups have been aggregated, SQL provides the HAVING clause:
-- ✅ CLEAN & VALID:SELECT department, AVG(salary) AS avg_salaryFROM employeesGROUP BY departmentHAVING AVG(salary) > 70000;5. The Definitive Showdown: WHERE vs HAVING 🥊
Understanding when to use WHERE versus HAVING is essential:
| Characteristic | WHERE | HAVING |
|---|---|---|
| Filters what? | Individual, raw rows | Collapsed, aggregated groups |
| When does it run? | BEFORE grouping & aggregation | AFTER grouping & aggregation |
| Can use aggregates? | ❌ No (WHERE SUM(x) > 10 is illegal) | ✅ Yes (HAVING COUNT(*) >= 5) |
| Performance | Fast (reduces rows before grouping) | Evaluates after collapsing groups |
Best Practice: Combining Both in the Same Query! 🚀
You can use both WHERE and HAVING together for maximum performance:
-- Scenario: Find departments with more than 2 employees hired after 2023:SELECT department, COUNT(*) AS recent_hiresFROM employeesWHERE hired_date >= '2023-01-01' -- 1. Discard older employees first!GROUP BY department -- 2. Group the remaining recent hiresHAVING COUNT(*) > 2; -- 3. Keep only departments with > 2 recent hires6. Updated Complete SQL Execution Order 📜
Now, we can update our mental model of the true SQL execution pipeline:
┌────────────────────────────────────────────────────────┐
│ UPDATED SQL EXECUTION ORDER │
├───────┬──────────────┬─────────────────────────────────┤
│ Step 1│ FROM │ Choose the source table(s) │
│ Step 2│ WHERE │ Filter raw individual rows │
│ Step 3│ GROUP BY │ Collapse rows into groups │
│ Step 4│ HAVING │ Filter collapsed groups │
│ Step 5│ SELECT │ Evaluate columns & expressions │
│ Step 6│ DISTINCT │ Eliminate duplicate output rows │
│ Step 7│ ORDER BY │ Sort final output rows │
│ Step 8│ LIMIT/OFFSET │ Paginate and truncate │
└───────┴──────────────┴─────────────────────────────────┘
Notice that HAVING runs at Step 4, while WHERE runs at Step 2!
Flashcard Checkpoint 🎴
What is the Golden Rule of columns listed in a SELECT clause when using GROUP BY?
What is the key difference between the WHERE clause and the HAVING clause?
HAVING filters aggregated groups after grouping and is designed specifically to test aggregate conditions.