MySQL Tutorial
The GROUP BY
statement in MySQL is used to group rows that have the same values in specified columns.
COUNT()
, SUM()
, AVG()
, MIN()
, or MAX()
to perform operations on groups of data.SELECT column_name, aggregate_function(column_name) FROM table_name WHERE condition GROUP BY column_name ORDER BY column_name;
column_name
→ The column(s) to group by.aggregate_function
→ Functions like COUNT()
, SUM()
, AVG()
, MIN()
, or MAX()
.WHERE
→ Filters rows before grouping.We have two tables:
Below is a selection from the "Students" table in the school_db database:
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
course_name |
course_name |
---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement find total students in each course.
city |
total_students |
---|---|
Delhi |
3 |
Mumbai |
3 |
Bangalore |
1 |
COUNT(*)
function counts the number of students in each city..GROUP BY city
groups the data by city.The following SQL statement finds total score of students with score above 70 by course.
Try it yourself
course_name |
total_score |
---|---|
Math |
85 |
Science |
95 |
History |
170 |
SUM(score)
calculates the total score of students scoring above 70.WHERE
filters data before applying GROUP BY
.