Tsallaka zuwa abun ciki
Justice Tech School

GROUP BY

GROUP BY splits rows into groups that share a value and runs the aggregate function on each group. Every selected column must be either in GROUP BY or inside an aggregate function.

Example
SELECT country, COUNT(*) AS students
FROM students
GROUP BY country
ORDER BY students DESC;

Result

country      | students
Nigeria      | 4
Ghana        | 2
South Africa | 1
Kenya        | 1
Example
SELECT country, ROUND(AVG(score), 1) AS average
FROM students
GROUP BY country
ORDER BY country;

Result

country      | average
Ghana        | 78.0
Kenya        | 64.0
Nigeria      | 84.0
South Africa | 59.0

Exercise

Group the rows by country.

SELECT country, COUNT(*) FROM students  BY country;

Quiz Test

What does GROUP BY do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.