Last modified: June 30, 2020

By default results are returned in the order that they’re stored in the database. But sometimes you’ll want to sort them differently. You can do that with the “ORDER BY” command at the end of your queries as shown in the expanded version of our SQL template here

SELECT [stuff you want to select] FROM [the table that it is in] ORDER BY [column you want to order by];

For example, the following query shows all the tracks ordered by the album_id. Try sorting it by other columns. Can you modify it to be sorted by their name?

You can list multiple things to ORDER BY, which is useful in the case where there are a lot of duplicate rows. In tracks for instance we can order all of the data by the composer and then by how long the song is (milliseconds) by listing both of those sorting columns.

Try reversing the order of the colums above (ORDER BY milliseconds, composer) and you’ll see what happens with the reverse prioritization of first sorting by milliseconds.

ASCending and DESCending Order Direction

By default things are sorted by ascending order. You can choose to reverse that order by specifying DESC, for descending. Similarly if you’d like to specify that you want ASCending you use ASC.

To test your skills, try getting all the tracks in order of most expensive to least expensive:

Written by: Dave Fowler
Reviewed by: Matt David


Get new data chapters sent right to your Inbox