01 / 21

GROUP BY &
HAVING

Learn to aggregate data into meaningful groups and filter those groups to extract powerful business insights from SQL databases.

Business Analytics

What Is Data Aggregation?

In business, raw data contains individual records: every sale, every transaction, every customer interaction. Aggregation means combining multiple rows into a single summary value: a total, an average, a count, or a maximum.

COUNT()
How many rows match?
SUM()
What is the total?
AVG()
What is the average?
MAX() / MIN()
Largest or smallest value?

Why GROUP BY Matters

Aggregate functions alone produce a single number for the entire table. But business questions are rarely that simple. You want totals per department, averages per region, or counts per product category.

Raw Rows Sales: East $50 Sales: West $80 Sales: East $70 Sales: West $60 Sales: East $90 Sales: North $40 GROUP BY region Grouped Result East SUM = $210 (3 rows) West SUM = $140 (2 rows) North SUM = $40 (1 row)

Introducing HAVING

Once you have grouped results, you often want to filter those groups. For instance: "Show me only regions with total sales above $100." This is where HAVING comes in.

East SUM = $210 West SUM = $140 North SUM = $40 HAVING
\( \text{SUM}(\text{sales}) > 100 \)
Result East: $210 ✓ passes West: $140 ✓ passes North: $40 ✕ filtered out

The SQL Syntax

SELECT column, \( \text{AGG\_FUNC}(\text{column}) \) FROM table_name WHERE condition_on_rows GROUP BY column HAVING \( \text{AGG\_FUNC}(\text{column}) \) > value ORDER BY column;

SQL Execution Order

1. FROM 2. WHERE Filters rows 3. GROUP BY Creates groups 4. HAVING Filters groups 5. SELECT 6. ORDER BY

WHERE vs HAVING

WHERE HAVING
Filters Individual rows Grouped results
Runs Before GROUP BY After GROUP BY
Can use aggregates? ✕ No ✓ Yes
Example WHERE \( \text{year} = 2024 \) HAVING \( \text{COUNT}(*) > 5 \)
Analogy Pick which students take the test Filter classes by average score

How to Apply GROUP BY & HAVING

1
Identify what you want to group by. Which column defines your "buckets"? (department, region, product_type)
2
Choose the aggregate function. Do you need COUNT, SUM, AVG, MAX, or MIN for each group?
3
Filter rows first with WHERE (if needed). Remove rows before grouping: date ranges, specific categories, etc.
4
Write the GROUP BY clause. List every non-aggregated column from SELECT.
5
Add HAVING to filter groups (if needed). Set conditions using aggregate functions.

Example 1: Basic GROUP BY

Question: How many employees work in each department?

SELECT department, \( \text{COUNT}(*) \) AS emp_count FROM employees GROUP BY department;
departmentemp_count
Marketing12
Engineering34
Sales21
Finance8

Example 2: Adding WHERE Before Grouping

Question: What is the total revenue per product category, but only for orders placed in 2024?

SELECT category, \( \text{SUM}(\text{revenue}) \) AS total_rev FROM orders WHERE order_year = 2024 GROUP BY category ORDER BY total_rev DESC;
categorytotal_rev
Electronics$482,000
Clothing$215,000
Home & Garden$98,500

Example 3: Filtering Groups with HAVING

Question: Which product categories had total 2024 revenue above $100,000?

SELECT category, \( \text{SUM}(\text{revenue}) \) AS total_rev FROM orders WHERE order_year = 2024 GROUP BY category HAVING \( \text{SUM}(\text{revenue}) \) > 100000 ORDER BY total_rev DESC;
categorytotal_revPasses HAVING?
Electronics$482,000✓ Yes
Clothing$215,000✓ Yes
Home & Garden$98,500✕ No

Using Multiple Aggregates

You can combine several aggregate functions in one query to get a richer picture of each group.

SELECT department, \( \text{COUNT}(*) \) AS headcount, \( \text{AVG}(\text{salary}) \) AS avg_salary, \( \text{MAX}(\text{salary}) \) AS top_salary FROM employees GROUP BY department HAVING \( \text{AVG}(\text{salary}) \) > 60000;

Grouping by Multiple Columns

You can group by more than one column to create finer-grained buckets.

SELECT region, product_type, \( \text{SUM}(\text{quantity}) \) AS total_qty FROM sales GROUP BY region, product_type;
regionproduct_typetotal_qty
EastWidget A340
EastWidget B210
WestWidget A180
WestWidget B295

The Golden Rule of GROUP BY

✓ Valid
SELECT dept, \( \text{COUNT}(*) \)
GROUP BY dept

"dept" is in GROUP BY
✕ Invalid
SELECT dept, name, \( \text{COUNT}(*) \)
GROUP BY dept

"name" is not grouped or aggregated

Why? Once rows are collapsed into groups, SQL doesn't know which individual "name" to display for a group of many employees. Every value must be summarized or be part of the grouping key.

Common Mistakes

✕ Using aggregate in WHERE
Writing \( \text{WHERE COUNT}(*) > 5 \) causes an error. Aggregates belong in HAVING, not WHERE.
✕ Missing column in GROUP BY
Selecting a non-aggregated column without grouping by it: SELECT dept, name, SUM(sales) GROUP BY dept. "name" is ambiguous.
✕ Confusing WHERE and HAVING
Using HAVING to filter individual rows (e.g., \( \text{HAVING year} = 2024 \)). This works but is slower: use WHERE for row-level filters.

Summary Cheat Sheet

Concept Purpose Syntax Placement
GROUP BY Split rows into groups After WHERE
HAVING Filter groups by aggregate After GROUP BY
\( \text{COUNT}(*) \) Number of rows per group In SELECT or HAVING
\( \text{SUM}(\text{col}) \) Total of a column per group In SELECT or HAVING
\( \text{AVG}(\text{col}) \) Average per group In SELECT or HAVING
WHERE Filter individual rows Before GROUP BY

Question 1 of 5

Which SQL clause is used to filter groups after aggregation?

Question 2 of 5

What is wrong with this query?

SELECT department, \( \text{COUNT}(*) \) FROM employees WHERE \( \text{COUNT}(*) > 3 \) GROUP BY department;

Question 3 of 5

Given this query:

SELECT city, AVG(salary) AS avg_sal FROM staff GROUP BY city HAVING \( \text{AVG}(\text{salary}) > 50000 \);

What does this return?

Question 4 of 5

In SQL's execution order, which happens first?

Question 5 of 5

You write: SELECT region, product, \( \text{SUM}(\text{sales}) \) FROM orders GROUP BY region;

Why will most databases reject this?