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

  • HAVING is used to filter groups, similar to how WHERE filters rows.


Result: (Departments with more than 1 student)

dept TotalStudents
IT 2
HR 2

🔹 Key Points

  1. GROUP BY groups rows that have the same values in specified columns.

  2. Usually combined with aggregate functions (COUNT, SUM, AVG, MIN, MAX).

  3. Use HAVING to filter groups after aggregation.

  4. Use ORDER BY with GROUP BY to sort grouped results.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *