MySQL GROUP BY Statement
MySQL GROUP BY Statement
The GROUP BY statement in MySQL is used to arrange identical data into groups.
It is commonly used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX() to summarize data.
🔹 Syntax
-
column1→ Column to group by -
aggregate_function()→ Function to summarize each group
🧠Example Table: students
| id | name | dept | marks |
|---|---|---|---|
| 1 | John | IT | 85 |
| 2 | Emma | HR | 90 |
| 3 | Raj | IT | 76 |
| 4 | Sara | Finance | 92 |
| 5 | Aman | HR | 88 |
🔹 Example 1: Count Students in Each Department
Result:
| dept | TotalStudents |
|---|---|
| IT | 2 |
| HR | 2 |
| Finance | 1 |
🔹 Example 2: Average Marks in Each Department
Result:
| dept | AvgMarks |
|---|---|
| IT | 80.5 |
| HR | 89 |
| Finance | 92 |
🔹 Example 3: Sum of Marks in Each Department
Result:
| dept | TotalMarks |
|---|---|
| IT | 161 |
| HR | 178 |
| Finance | 92 |
🔹 GROUP BY with HAVING Clause
-
HAVINGis used to filter groups, similar to howWHEREfilters rows.
Result: (Departments with more than 1 student)
| dept | TotalStudents |
|---|---|
| IT | 2 |
| HR | 2 |
🔹 Key Points
-
GROUP BY groups rows that have the same values in specified columns.
-
Usually combined with aggregate functions (
COUNT,SUM,AVG,MIN,MAX). -
Use HAVING to filter groups after aggregation.
-
Use ORDER BY with GROUP BY to sort grouped results.
