ORDER BY

Sorting by two columns

SQLite in your browser
Lesson concept What you'll do
1 / 4

Sort by one column, then by another for rows that tie.

List both after ORDER BY, each with its own direction.

The database
11 rows
book_idtitleauthorgenreyearpages
1The Great GatsbyF. Scott FitzgeraldFiction1925180
2The Fault in Our StarsJohn GreenRomance2012313
3Angels & DemonsDan BrownThriller2000616
4MockingjaySuzanne CollinsScience Fiction2010390
5The ShiningStephen KingHorror1977447
6Charlotte's WebE.B. WhiteChildren1952184
7Pride and PrejudiceJane AustenRomance1813432
8The Fellowship of the RingJ.R.R. TolkienFantasy1954423
9The Time MachineH.G. WellsScience Fiction1895118
10EmmaJane AustenRomance1815474
11CarrieStephen KingHorror1974200
Click a name to type it
Your query
 
Hint: click the green edit button on the board, or type it yourself
Query output Ready to run

Run your query to see the result table.

Press the green Run button or Ctrl+Enter.

Study notes

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, genre sorts by pages first, and genre hardly ever matters. Put the main grouping first.

  • Where does DESC go?

    After the column it applies to. Each column has its own direction: ORDER BY genre, pages DESC is genre A to Z, then longest first.

  • Can I sort by a column I don't show?

    Yes: SELECT title FROM books ORDER BY year works. 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 SORTBY function works the same way.

Know someone fighting with a spreadsheet? Send them this page.