MySQL Tutorial
The MySQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used..
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Let's put these statements into real use.
We've a table named Students in our database that contains the following records:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | JAVA |
2 | SAM | Python |
3 | Sara | HTML | 4 | Rim | Java |
5 | Micheal | SQL |
6 | Lara | JAVA |
Now we will fetch records from the Students table with GROUP.
The following SQL statement lists the number of Students in GROUP SUBJECT.
SELECT SUBJECT, Count(ROLL_NO) FROM Students
GROUP BY SUBJECT;
The above SELECT statement selects SUBJECT and COUNT the NUMBER for SUBJECTS from Students table.
SUBJECT | COUNT(ROLL_NO) |
---|---|
Java | 3 |
HTML | 1 |
Python | 1 |
SQL | 1 |
The following SQL statement Counts the number of Students in each Subject, sorted low to High:
SELECT SUBJECT, Count(ROLL_NO) FROM Students
GROUP BY SUBJECT
ORDER BY COUNT(ROLL_NO) ASC;
The above SELECT statement selects SUBJECT and COUNT the NUMBER for SUBJECTS from Students table and sorted low to High:
SUBJECT | COUNT(ROLL_NO) |
---|---|
HTML | 1 |
Python | 1 |
SQL | 1 |
Java | 3 |