liveBook · Manning

Order by clause

As explained in Grokking Relational Database Design

An ORDER BY clause specifies the ordering applied to rows returned by an SQL query.

An ORDER BY clause sorts the rows returned by an SQL query. For example, a movie application can show the highest-rated movies first by sorting rating values in descending order. section 7.9

Show the 30 highest-rated movies

SELECT * FROM movie ORDER BY rating DESC LIMIT 30; The database reads movie rows, selects the columns, sorts them by rating from highest to lowest, and then keeps the first 30 rows. DESC means descending order. section 7.9

Keep these practical rules in mind:

  • Place ORDER BY after the rows and columns have been selected; LIMIT can then restrict the sorted result. section 7.9
  • Sorting millions of rows repeatedly can slow an application, so an index on the sorted column may improve performance. section 7.9
-- comment: works for MySQL, MariaDB, 
-- comment: PostgreSQL and SQLite
-- comment: consult ChatGPT on adaptations 
-- comment: for other RDBMS
SELECT *
 FROM movie
 ORDER BY rating DESC
 LIMIT 30;

Run the complete movie query to see descending sorting combined with a 30-row limit. section 7.9

How Grokking Relational Database Design covers it

How deep it goes
Explains sorting, descending order, clause execution, LIMIT interaction, and index-related performance concerns.
Examples
Demonstrates a movie query ordering ratings descending and limiting the result to 30 rows.
What you can do after
Apply it via SQL to sort query results and combine ordering with LIMIT for ranked lists.
How it connects
Connects ORDER BY with SELECT, FROM, LIMIT, indexes, WHERE, and B-trees.

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 Grokking Relational Database Design. The section links point to the parts of the book it draws on.