Back to community
Computer ScienceClass 12 (CBSE)

What does GROUP BY actually do in an SQL query?

I understand SELECT and WHERE but GROUP BY does not make sense to me. When my teacher uses it with COUNT I get lost. Can someone explain it simply?

TuitionsInIndia Study Desk 43 135d ago
Need help with Computer Science? Browse tutor profiles and check whether they teach your subject and class.

1 answer

1

GROUP BY collapses many rows into groups so you can summarise each group with one result. It is used with aggregate functions like COUNT, SUM, AVG, MAX and MIN. Imagine a table of students with a 'city' column. 'SELECT city, COUNT(*) FROM students GROUP BY city' puts all rows with the same city into one bucket and then counts how many are in each bucket, giving one row per city. Without GROUP BY, COUNT(*) would count the whole table as a single number. A simple rule: every column in your SELECT that is not inside an aggregate function must appear in the GROUP BY. So GROUP BY answers questions like how many students per city or total sales per product.

TuitionsInIndia Study DeskEditorial
Reviewed answer · 135d ago

Sign in as a tutor to answer this doubt.