Sorting data in SQL with the ORDER BY clause is a great way to arrange your data just how you want it. Imagine you've got a bunch of music chart data.
| year_rank | year | artist | song_title |
|---|---|---|---|
| 1 | 2013 | Taylor Swift | I Knew You Were Trouble |
| 2 | 2013 | Justin Timb | Mirrors |
| 3 | 2013 | Rihanna | Stay |
| ... | ... | ... | ... |
| 1 | 2012 | Adele | Rolling in the Deep |
| 2 | 2012 | Maroon 5 | One More Night |
| 3 | 2012 | Carly Rae | Call Me Maybe |
| ... | ... | ... | ... |
At first, it's all over the place. You'll get the songs in the order they're stored in the database, which might not be super helpful.
SELECT * FROM music_chart;
Now, say you want to line them up alphabetically by the artist's name. Here's how you do it:
SELECT * FROM music_chart ORDER BY artist;
This lines up everything from A to Z by the artist's name. That's ascending order, and it's the usual way SQL sorts stuff. If it's numbers, it starts with the smallest and goes up.
Want to flip it around? Just add DESC after the column name. Like this:
SELECT * FROM music_chart WHERE year = 2013 ORDER BY year_rank DESC;
This ORDER BY is the same as clicking on filter when using Excel and then ordering a specific column by ascending or descending order.
Sorting with Multiple Columns:
You can also sort by more than one column. Say you want the newest songs first, but within each year, you want them ordered by their rank:
SELECT * FROM music_chart
WHERE year_rank <= 3 ORDER BY year DESC, year_rank;
Here's a cool trick: Instead of column names, you can use numbers to refer to the columns in your SELECT statement. Like, 1 for the first column, 2 for the second, and so on. Your query will look way more cleaner this way!
SELECT * FROM music_chart
WHERE year_rank <= 3 ORDER BY 2 DESC, 1;
Now you know how to use ORDER BY 🎉 and do it across multiple columns.
Time to practice!