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?

Asked by Rohan Verma 39 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

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.

M
Meera Joshi
335 pts· 45d ago

Sign in as a tutor to answer this doubt.