#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
Step 7
3 min read

GROUP BY

Learn how to group data and calculate totals for each group.

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:

  1. In GROUP BY, OR
  2. 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
idnameagegrade
1Alice20A
2Bob22B
3Charlie21A
4David23B
4 rows
SQL Editor
Loading...

GROUP BY with AVG

Average age per grade. Try adding MIN and MAX!

Source Table: students
idnameagegrade
1Alice20A
2Bob22B
3Charlie21A
4David23B
4 rows
SQL Editor
Loading...

Multiple Aggregates

Get all stats for each grade!

Source Table: students
idnameagegrade
1Alice20A
2Bob22B
3Charlie21A
4David23B
4 rows
SQL Editor
Loading...

Finished this topic?

Mark it complete to track your progress and maintain your streak!