ImplementationGROUP BY

Structured Query Language is used to allow database developers to generate queries and interrogate the data held in a database. SELECT, FROM, WHERE, AND and OR are key areas of SQL.

Part ofComputing ScienceDatabase design and development

GROUP BY

GROUP BY is another SQL keyword that we can use to group a set of records in our query by some given criteria. It gathers any data that is identical in the field we want to GROUP BY.

This criteria can change based on what field we want to GROUP BY.

In the following example, we will group pupils by their class and order them by their class in ascending order.

SELECT pupilID, firstname, surname, class, pastoralCareTeacher, meritPoints
FROM Pupil
GROUP BY class
ORDER BY class ASC;

Note: whenever a single query has both GROUP BY and ORDER BY clauses, the GROUP BY clause must precede the ORDER BY clause. If you do not do this, you will get an error.

If we run the query above, a table of results will be returned

Our table would look this this:

PupilIDFirst NameSurnameClassPastoral Care TeacherMerit Points
0005PawelMcTavish1I1Mrs Aitken19
0002DavidBoland1I2Mrs Aitken12
0003AmyJones1M1Mr Gilchrist55
0010ThomasGlacney1M1Miss Armstrong91
0006AntoniaGallagher1M2Mr Gilchrist21
0001ZainabSingh1T1Mr Harley74
0004JamesMcNamee1T1Mr Harley88
0007AmyMcNamee1T1Mr Harley63
0008AyshaMatazinadze1T1Mr Harley45
0009BeatricePanner1T2Mr Harley77
PupilID0005
First NamePawel
SurnameMcTavish
Class1I1
Pastoral Care TeacherMrs Aitken
Merit Points19
PupilID0002
First NameDavid
SurnameBoland
Class1I2
Pastoral Care TeacherMrs Aitken
Merit Points12
PupilID0003
First NameAmy
SurnameJones
Class1M1
Pastoral Care TeacherMr Gilchrist
Merit Points55
PupilID0010
First NameThomas
SurnameGlacney
Class1M1
Pastoral Care TeacherMiss Armstrong
Merit Points91
PupilID0006
First NameAntonia
SurnameGallagher
Class1M2
Pastoral Care TeacherMr Gilchrist
Merit Points21
PupilID0001
First NameZainab
SurnameSingh
Class1T1
Pastoral Care TeacherMr Harley
Merit Points74
PupilID0004
First NameJames
SurnameMcNamee
Class1T1
Pastoral Care TeacherMr Harley
Merit Points88
PupilID0007
First NameAmy
SurnameMcNamee
Class1T1
Pastoral Care TeacherMr Harley
Merit Points63
PupilID0008
First NameAysha
SurnameMatazinadze
Class1T1
Pastoral Care TeacherMr Harley
Merit Points45
PupilID0009
First NameBeatrice
SurnamePanner
Class1T2
Pastoral Care TeacherMr Harley
Merit Points77

The table above has all pupils grouped by their class and ordered by their class in ascending order (1I1, 1I2, 1M1, 1M2, 1T1, 1T2).