AI Hints
Homeโ€บSQL Tutorialโ€บSorting Results
SQL ยท Lesson 16 of 126

Sorting with ORDER BY

Put results in order.

โฑ 2 min readโ–ถ Video at 23:03๐ŸŽ“ Free
Watch this lesson in the SQL courseWatch on YouTube โ†—Full SQL course

Helen asks, what are my cheapest books? To answer, the rows need to be in order, from cheapest to most expensive. Without instructions, a database can return rows in any order it likes. So when order matters, you must ask for it.

Sorting with ORDER BY
From the video: Sorting with ORDER BY
  • What are my cheapest books?
  • Rows have no order by default
  • Ask for the order you want

Cheapest first

Order by goes after where, and before limit. Order by price sorts from the smallest price to the largest. That's called ascending, and it's the default. Run it. Garden of Small Things is the cheapest book, at eight ninety nine.

query.sqlsql
SELECT title, price
FROM books
ORDER BY price
LIMIT 5;
Output
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚         title          โ”‚ price โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Garden of Small Things โ”‚ 8.99  โ”‚
โ”‚ Stars Over Lagos       โ”‚ 9.99  โ”‚
โ”‚ Letters to Lisbon      โ”‚ 10.49 โ”‚
โ”‚ Murder at Mill Lane    โ”‚ 10.99 โ”‚
โ”‚ Wild Coast             โ”‚ 11.49 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Most expensive first

To flip the order, add the word DESC, short for descending. Now the biggest price comes first. Run it. Python for Curious Minds is the most expensive book. Order by, then limit, is how you get a top three, or a top ten.

query.sqlsql
SELECT title, price
FROM books
ORDER BY price DESC
LIMIT 3;
Output
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚          title           โ”‚ price โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Python for Curious Minds โ”‚ 34.99 โ”‚
โ”‚ Data for Everyone        โ”‚ 31.99 โ”‚
โ”‚ SQL in a Weekend         โ”‚ 29.99 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

Order by sorts the rows, smallest first by default, or largest first with DESC. Next, sorting by more than one column.

Key takeaways
  • ORDER BY sorts rows
  • Smallest first by default
  • DESC for largest first
Next up: Sorting by Two Columns โ€” ties, and the full query order