Sorting results using ORDER BY.

By Alan Hylands — 2 minute read

Ordering and arranging our results.

SQL isn't just about grabbing rows of data from our database tables. It's also useful for arranging and sorting the order of our results to make them easier to analyse.

We can sort by specific columns and attributes by using the ORDER BY keyword. For example, we could sort our footballers by alphabetical order on their surnames as so:

SELECT FirstName, Surname 
FROM footballers
ORDER BY Surname;
PlayerIDFirstNameSurname
1TrentAlexander-Arnold
3HarryKane
4MoSalah
2WilfredZaha

The other way around.

We could reverse the order of the sort by adding the additional keyword DESC at the end of the query. For our footballer example, that would put Wilfred Zaha first in our results and Trent Alexander-Arnold last.

SELECT FirstName, Surname 
FROM footballers
ORDER BY Surname DESC;
PlayerIDFirstNameSurname
2WilfredZaha
4MoSalah
3HarryKane
1TrentAlexander-Arnold
Try the next lesson