Advertisement
Google Ad Slot: content-top
MySQL GROUP BY
MySQL GROUP BY
The GROUP BY statement in MySQL is used to group rows that have the same values in specified columns.
- It is often used with aggregate functions like
COUNT(),SUM(),AVG(),MIN(), orMAX()to perform operations on groups of data. - It organizes the result set into groups based on one or more columns.
GROUP BY Syntax
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 likeCOUNT(),SUM(),AVG(),MIN(), orMAX().WHERE→ Filters rows before grouping.
MySQL GROUP BY Examples
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 |
courses Table
course_name |
course_name |
|---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement find total students in each course.
Output:
city |
total_students |
|---|---|
Delhi |
3 |
Mumbai |
3 |
Bangalore |
1 |
Explanation:
- The
COUNT(*)function counts the number of students in each city.. GROUP BY citygroups the data by city.
GROUP BY With JOIN Example
The following SQL statement finds total score of students with score above 70 by course.
Output:
course_name |
total_score |
|---|---|
Math |
85 |
Science |
95 |
History |
170 |
Explanation:
SUM(score)calculates the total score of students scoring above 70.WHEREfilters data before applyingGROUP BY.