01 / 21

SQL
GROUP BY

Learn how to organize rows into groups based on column values and compute aggregate results for each group.

SQL

What Is GROUP BY?

GROUP BY is a SQL clause that collapses multiple rows sharing the same value in one or more columns into a single summary row. Instead of seeing every individual record, you see one row per distinct group.

Why GROUP BY Matters

Summarize
Compute totals, averages, and counts across categories without writing separate queries.
Analyze
Find trends and patterns: sales by region, scores by student, orders by month.
Report
Build dashboards and reports that show one number per category instead of thousands of raw rows.

Rows to Groups: A Visual

Raw Rows Math   Alice   90 Science   Bob   85 Math   Carol   78 English   Dave   92 Science   Eve   88 Math   Frank   95 English   Grace   87 GROUP BY subject Grouped Result Math
3 students · \(\text{AVG} = 87.7\)
Science
2 students · \(\text{AVG} = 86.5\)
English
2 students · \(\text{AVG} = 89.5\)

The GROUP BY Syntax

SELECT column, AGG(column) FROM table WHERE condition -- filter rows BEFORE grouping GROUP BY column HAVING condition -- filter groups AFTER grouping ORDER BY column;

Common Aggregate Functions

COUNT()
Number of rows in each group. Use COUNT(*) for all rows or COUNT(col) for non-NULL values.
SUM()
Adds up all values in the column within each group.
AVG()
Computes the arithmetic mean of values in each group.
MAX()
Returns the largest value within each group.
MIN()
Returns the smallest value within each group.

WHERE vs HAVING

WHERE HAVING
When it runs Before grouping After grouping
Filters Individual rows Entire groups
Can use aggregates? No Yes
Example WHERE \(\text{score} > 60\) HAVING \(\text{AVG}(\text{score}) > 80\)

SQL Execution Order

FROM WHERE GROUP BY HAVING SELECT ORDER BY Pick the table(s) Filter individual rows Collapse rows into groups Filter groups by aggregate Choose columns & compute aggregates Sort the final result 1 2 3 4 5 6

How to Write a GROUP BY Query

1
Identify the question. What summary do you need? "Total sales by region" tells you the grouping column (region) and the aggregate (SUM of sales).
2
Write SELECT with GROUP BY columns. List every non-aggregated column first, then add the aggregate function.
3
Add FROM and WHERE. Filter out unwanted rows before grouping to keep results clean.
4
Add HAVING if needed. Use HAVING only when you need to filter based on an aggregate result.
5
ORDER BY. Sort the grouped results. You can sort by aggregate values (e.g., ORDER BY SUM(sales) DESC).

Example 1: Count by Category

Question: How many students are in each department?

SELECT department, COUNT(*) AS num_students FROM students GROUP BY department;
departmentnum_students
Computer Science42
Mathematics28
English35

Example 2: SUM with WHERE

Question: What are total sales per product for the year 2024?

SELECT product, SUM(amount) AS total_sales FROM orders WHERE order_year = 2024 GROUP BY product ORDER BY total_sales DESC;
producttotal_sales
Laptop$124,500
Tablet$87,200
Phone$63,800

Example 3: Filtering with HAVING

Question: Which cities have more than 100 customers?

SELECT city, COUNT(*) AS customer_count FROM customers GROUP BY city HAVING COUNT(*) > 100 ORDER BY customer_count DESC;
citycustomer_count
New York312
Los Angeles245
Chicago178

Grouping by Multiple Columns

You can group by two or more columns to create finer-grained groups. Each unique combination of values becomes its own group.

SELECT department, semester, AVG(grade) AS avg_grade FROM enrollments GROUP BY department, semester;
departmentsemesteravg_grade
CSFall3.42
CSSpring3.58
MathFall3.21
MathSpring3.35

Putting It All Together

Question: For active employees, which departments have an average salary above $70,000? Sort highest first.

SELECT department, COUNT(*) AS emp_count, AVG(salary) AS avg_salary FROM employees WHERE status = 'active' GROUP BY department HAVING AVG(salary) > 70000 ORDER BY avg_salary DESC;

Common Mistakes

✕ Non-aggregated column in SELECT
Selecting a column that is not in GROUP BY and not in an aggregate function. This causes an error in most databases.
✕ Using WHERE instead of HAVING
Writing WHERE \(\text{COUNT}(*) > 5\) instead of HAVING \(\text{COUNT}(*) > 5\). WHERE cannot use aggregate functions.
✕ Forgetting GROUP BY entirely
Using an aggregate in SELECT alongside a plain column without GROUP BY. The database does not know how to group.

Quick Reference Table

Clause Purpose Uses Aggregates?
SELECT Choose columns and compute aggregates Yes
FROM Specify source table(s) No
WHERE Filter rows before grouping No
GROUP BY Define the grouping columns No
HAVING Filter groups after aggregation Yes
ORDER BY Sort the final result Yes

Question 1 of 5

Which clause filters groups after GROUP BY has run?

Question 2 of 5

Given this query, what is wrong?

SELECT department, name, COUNT(*) FROM employees GROUP BY department;

Question 3 of 5

You want to find the average score per class, but only for classes with more than 20 students. Which query is correct?

Question 4 of 5

What does COUNT(*) count?

Question 5 of 5

In SQL's logical execution order, which runs first?