Home »
MySQL
MySQL GROUP BY Clause
MySQL | GROUP BY Clause: Learn about the MySQL GROUP BY Clause, with its explanation, syntax, and query examples.
Submitted by Apurva Mathur, on September 08, 2022
GROUP BY Clause
As the name suggests, the GROUP BY clause is used to group identical data into one set. This clause is always used with SELECT statements, and MySQL functions like (count(), avg(), sum(), etc). When we want to group some columns then in such cases we use this clause.
GROUP BY Clause Syntax
SELECT column_1, aggregate_function (column_2)
FROM table_name
WHERE condition
GROUP BY column_1, column_2;
Let us take some examples;
GROUP BY Clause Examples
Suppose we have a table named "student_details" and inside that table, we have the following columns;
Case 1: As we can see in the table we have a student from different years, now if want to know the total summary of the student and year like how many students are totaled in the respective year, in such case we will use the following query.
SELECT count(Id) AS total_students, year
FROM student_details
GROUP BY year;
As you can see by using the GROUP BY clause we have a summary of students and years, in the query, I have also AS clause to provide a temporary name.
Case 2: Suppose I want to know, how many students are in respective departments. Then in such case, I will write,
SELECT count (ID), student_department
FROM student_details
GROUP BY student_department
ORDER BY count (Id) DESC;
Here in this query, I have used the ORDER BY clause with the GROUP BY to arrange the result in alphabetical order.