What is GROUP BY?
GROUP BY puts rows into groups. Like sorting students by their grade.
Without GROUP BY: You see every row. With GROUP BY: You see one row per group with totals.
How GROUP BY Works
Basic Syntax
SELECT column, COUNT(*) FROM table GROUP BY column;Example 1: Count Students by Grade
How many students in each grade?
SELECT grade, COUNT(*) AS total FROM students GROUP BY grade;Example 2: Average Age by Grade
What's the average age in each grade?
SELECT grade, AVG(age) AS avg_age FROM students GROUP BY grade;Example 3: Multiple Aggregates
Get count, min, max, and average for each grade:
SELECT
grade,
COUNT(*) AS total,
MIN(age) AS youngest,
MAX(age) AS oldest,
AVG(age) AS avg_age
FROM students
GROUP BY grade;Important Rule
In SELECT, every column must be:
- In GROUP BY, OR
- Inside an aggregate (COUNT, SUM, AVG, MIN, MAX)
-- Wrong: name is not grouped or aggregated
SELECT name, grade, COUNT(*) FROM students GROUP BY grade;
-- Correct: only grade and COUNT
SELECT grade, COUNT(*) FROM students GROUP BY grade;Try It Below
Use the playground to practice:
SELECT grade, COUNT(*) FROM students GROUP BY grade;SELECT grade, AVG(age) FROM students GROUP BY grade;
What Comes Next
Next: Learn HAVING to filter groups after GROUP BY.
Try GROUP BY
Count students in each grade. Try: SELECT grade, COUNT(*) FROM students GROUP BY grade;
Source Table: students
| id | name | age | grade |
|---|---|---|---|
| 1 | Alice | 20 | A |
| 2 | Bob | 22 | B |
| 3 | Charlie | 21 | A |
| 4 | David | 23 | B |
4 rows
SQL Editor
Loading...
GROUP BY with AVG
Average age per grade. Try adding MIN and MAX!
Source Table: students
| id | name | age | grade |
|---|---|---|---|
| 1 | Alice | 20 | A |
| 2 | Bob | 22 | B |
| 3 | Charlie | 21 | A |
| 4 | David | 23 | B |
4 rows
SQL Editor
Loading...
Multiple Aggregates
Get all stats for each grade!
Source Table: students
| id | name | age | grade |
|---|---|---|---|
| 1 | Alice | 20 | A |
| 2 | Bob | 22 | B |
| 3 | Charlie | 21 | A |
| 4 | David | 23 | B |
4 rows
SQL Editor
Loading...