MySQL GROUP BY

Last Updated: March 14, 2022

GROUP BY clause allows you to group a set of rows into groups

GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s); 

Example

Student table with student_name, subject, and marks

groupby table 1

Get the average marks of the subjects

SELECT subject, AVG(marks) FROM students
GrOUP BY subject;
groupby result

To get the average marks of each student, you can run the following query

SELECT student_name, AVG(marks) FROM students
GrOUP BY student_name;
groupby result2

Following aggregate function can be used in GROUP BY queries

  • AVG
  • COUNT
  • SUM
  • MAX
  • MIN
Test