liveBook · Manning

Order by clause

As explained in Learn SQL in a Month of Lunches

ORDER BY is the SQL keyword sequence that introduces a clause specifying the order of query results.

Use ORDER BY when a query needs predictable result order—for example, listing title names alphabetically instead of accepting whatever order the database returns. Add it after the other main query clauses; sorting happens after the result set is produced. section 4.1.1

SELECT
    TitleName,
    Price
FROM title
ORDER BY
    TitleName;

Sorts selected title names alphabetically by adding ORDER BY TitleName to a complete query. section 4.1.1

Ascending order is implicit: text runs from A to Z and numbers from low to high. Write DESC for descending order, or ASC for clarity. Each sort column can have its own direction. section 4.1.3

Sort by a primary column and a tie-breaker

SELECT TitleName, Advance, Royalty FROM title ORDER BY Advance DESC, Royalty ASC; This puts the largest advances first; rows with equal advances are then ordered by royalty from smallest to largest. section 4.1.2 section 4.1.3

You can sort by a selected column’s alias, such as NameOfTheBook, or by its numeric position in SELECT. Positional sorting is convenient for quick queries but becomes unclear and fragile when the selected columns change. section 4.1.1 section 4.1.5

SELECT
    TitleName,
    PublicationDate
FROM title
ORDER BY PublicationDate DESC
LIMIT 3;

Combines descending date order with LIMIT to return the three most recently published titles. section 4.2.1

When limiting results, put LIMIT after ORDER BY so the returned rows represent a meaningful top or bottom sample; without ordering, a limited result can be random and unpredictable. Sorting very large result sets can also consume substantial processor and memory resources. section 4.2.1 section 4.1.1

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains single and multiple columns, directions, aliases, positions, clause placement, LIMIT interaction, and performance cautions.
Examples
Demonstrates title-name sorting, advance-and-royalty tie-breaking, mixed directions, aliases, positions, and three newest publications.
What it assumes
Assumes basic SELECT queries and column names while teaching sort direction, tie-breaking, aliases, and clause order.
What you can do after
Apply it via SQL to sort one or more columns, choose directions, rank limited results, and avoid fragile positional notation.
How it connects
Connects SELECT columns and aliases with LIMIT, set operators, and the final stage of query evaluation.

Also explained in

Compare how 3 books explain order by clause →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.