GROUP BY
In MySQL, the GROUP BY clause is used to group rows that have the same values in specified columns. This is often used in conjunction with aggregate functions, such as COUNT, SUM, AVG, MAX, or MIN, to perform calculations on each group of rows.
Syntax
SELECT column1, column2,
FROM table_name
WHERE condition
GROUP BY column1, column2;Example
Suppose we have a Students table as shown below:
Image scaled to 65%
Now, suppose you want to find out how many students are enrolled in each subject. In order to do this, we formulate the following query:
SELECT course, COUNT(*) AS student_count
FROM Students
GROUP BY course;Database Exercise
Database Schema:
-- Database schema would be rendered hereExercise Script:
-- Exercise script would be rendered hereAvailable actions: Execute
The result of this query would be a table showing the count of students for each course:
Image scaled to 65%
Last updated on