ORDER BY

Learn SQL

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.

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 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:


If you're finding this SQL Tutorial helpful, you may also enjoy our product Chartio. Chartio is on a mission to enable anyone in a company with the power of a data analyst. To do so we've built a very user friendly interface for people to explore and visualize data with either SQL, or our drag and drop Visual SQL. You can connect to all of your different data sources, and quickly create visuals and dashboards to share with your team. Give us a spin, there's a 2 week free trial.