SQL
GROUP BY
Learn how to organize rows into groups based on column values and compute aggregate results for each group.
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
Rows to Groups: A Visual
The GROUP BY Syntax
Common Aggregate Functions
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
How to Write a GROUP BY Query
Example 1: Count by Category
Question: How many students are in each department?
| department | num_students |
|---|---|
| Computer Science | 42 |
| Mathematics | 28 |
| English | 35 |
Example 2: SUM with WHERE
Question: What are total sales per product for the year 2024?
| product | total_sales |
|---|---|
| Laptop | $124,500 |
| Tablet | $87,200 |
| Phone | $63,800 |
Example 3: Filtering with HAVING
Question: Which cities have more than 100 customers?
| city | customer_count |
|---|---|
| New York | 312 |
| Los Angeles | 245 |
| Chicago | 178 |
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.
| department | semester | avg_grade |
|---|---|---|
| CS | Fall | 3.42 |
| CS | Spring | 3.58 |
| Math | Fall | 3.21 |
| Math | Spring | 3.35 |
Putting It All Together
Question: For active employees, which departments have an average salary above $70,000? Sort highest first.
Common Mistakes
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?
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?