Sorting with ORDER BY
Put results in order.
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.

- 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.
SELECT title, price
FROM books
ORDER BY price
LIMIT 5;โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโ โ 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.
SELECT title, price
FROM books
ORDER BY price DESC
LIMIT 3;โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโ โ 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