ImplementationORDER 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

ORDER BY

ORDER BY is an SQL Keyword used to allow the ordering of results in either ascending or descending order.

SELECT First Name, Surname, Class FROM Pupil
ORDER BY Surname ASC;

This would return:

First NameSurnameClass
DavieBoland1I2
AntoniaGallagher1M2
TomGlacney1M1
AmyJones1M1
TabisoMatazinadze1T1
JamesMcNamee1T1
AmyMcNamee1T1
PawelMcTavish1I1
BeatricePanner1T2
NisaSingh1T1
First NameDavie
SurnameBoland
Class1I2
First NameAntonia
SurnameGallagher
Class1M2
First NameTom
SurnameGlacney
Class1M1
First NameAmy
SurnameJones
Class1M1
First NameTabiso
SurnameMatazinadze
Class1T1
First NameJames
SurnameMcNamee
Class1T1
First NameAmy
SurnameMcNamee
Class1T1
First NamePawel
SurnameMcTavish
Class1I1
First NameBeatrice
SurnamePanner
Class1T2
First NameNisa
SurnameSingh
Class1T1

By default, the surname column/field is sorted in ascending order but the ASC keyword is shown to exemplify its existence. To sort in descending order, add DESC at the end of the statement.

SELECT First Name, Surname, Class FROM Pupil
ORDER BY Surname DESC;

This would return:

First NameSurnameClass
NisaSingh1T1
BeatricePanner1T2
PawelMcTavish1I1
JamesMcNamee1T1
AmyMcNamee1T1
TabisoMatazinadze1T1
AmyJones1M1
TomGlacney1M1
AntoniaGallagher1M2
DavieBoland1I2
First NameNisa
SurnameSingh
Class1T1
First NameBeatrice
SurnamePanner
Class1T2
First NamePawel
SurnameMcTavish
Class1I1
First NameJames
SurnameMcNamee
Class1T1
First NameAmy
SurnameMcNamee
Class1T1
First NameTabiso
SurnameMatazinadze
Class1T1
First NameAmy
SurnameJones
Class1M1
First NameTom
SurnameGlacney
Class1M1
First NameAntonia
SurnameGallagher
Class1M2
First NameDavie
SurnameBoland
Class1I2

Sorting multiple columns

It is possible to apply a sort on more than one column.

The first sort would be applied in its entirety, with the second sort only applied if two records in the column used for the first sort have the same value.

SELECT First Name, Class, Merit Points FROM Pupil
ORDER BY Class DESC, Merit Points ASC;

Would return:

N5 Computing Science first name table

The class column is fully sorted in descending order. Within each class group, the Merit Points column is sorted in ascending order.