Course outline · 0% complete

0/29 lessons0%

Course overview →

ORDER BY: Putting Rows in Order

lesson 3-1 · ~11 min · 6/29

Quiz

Warm-up from lesson 2-1: in the movies table, which query finds the movies released before 2000?

Sorting

So far, rows have come back in the order they were inserted. Never rely on that: without an explicit order, the database is free to return rows however it likes. When order matters, and it usually does (a newest-first feed, a cheapest-first shop page, a leaderboard: each is just a sorted query), say so with ORDER BY:

SELECT title, rating FROM movies ORDER BY rating DESC;
  • DESC means descending (biggest first).
  • ASC means ascending (smallest first) and is the default, so ORDER BY year sorts oldest first.
  • Text columns sort alphabetically.

ORDER BY goes after the WHERE clause if you have one: SELECT ... FROM ... WHERE ... ORDER BY ....

Code exercise · sql

Run it. Same five movies from unit 2, now ranked best-rated first.

Sorting by more than one column

List several columns and the database uses the second as a tie-breaker for the first, the third for the second, and so on:

SELECT genre, rating, title FROM movies
ORDER BY genre, rating DESC;

Rows are grouped alphabetically by genre first. Inside each genre, the higher rating comes first. Each column gets its own ASC/DESC.

Code exercise · sql

Your turn. Sort the movie titles alphabetically, printing only the title column. Alien should be first, The Matrix last.

Code exercise · sql

Drill. Sort the movies by genre alphabetically, and inside each genre put the newest movie first. Print genre, year, title. This needs two sort columns with different directions.