Sorting by two columns
Sort by one column, then by another for rows that tie.
List both after ORDER BY, each with its own direction.
Show the author and title of every book, sorted by author (A to Z), and by title within each author.
| book_id | title | author | genre | year | pages |
|---|---|---|---|---|---|
| 1 | The Great Gatsby | F. Scott Fitzgerald | Fiction | 1925 | 180 |
| 2 | The Fault in Our Stars | John Green | Romance | 2012 | 313 |
| 3 | Angels & Demons | Dan Brown | Thriller | 2000 | 616 |
| 4 | Mockingjay | Suzanne Collins | Science Fiction | 2010 | 390 |
| 5 | The Shining | Stephen King | Horror | 1977 | 447 |
| 6 | Charlotte's Web | E.B. White | Children | 1952 | 184 |
| 7 | Pride and Prejudice | Jane Austen | Romance | 1813 | 432 |
| 8 | The Fellowship of the Ring | J.R.R. Tolkien | Fantasy | 1954 | 423 |
| 9 | The Time Machine | H.G. Wells | Science Fiction | 1895 | 118 |
| 10 | Emma | Jane Austen | Romance | 1815 | 474 |
| 11 | Carrie | Stephen King | Horror | 1974 | 200 |
Run your query to see the result table.
Press the green Run button or Ctrl+Enter.
How ORDER BY works
How do I sort by two columns?
ORDER BY genre,pages DESC List them with a comma. Rows are sorted by the first column, and the second only decides the order of rows that tie on the first.
Does the order of the columns matter?
Yes.
ORDER BY pages, genresorts by pages first, and genre hardly ever matters. Put the main grouping first.Where does
DESCgo?After the column it applies to. Each column has its own direction:
ORDER BY genre, pages DESCis genre A to Z, then longest first.Can I sort by a column I don't show?
Yes:
SELECT title FROM books ORDER BY yearworks. It's often clearer to show it, though.How is this like Excel?
It's Sort with "Add Level": first sort by genre, then by pages. The
SORTBYfunction works the same way.
Know someone fighting with a spreadsheet? Send them this page.