AI Hints
Home›PostgreSQL Tutorial›Querying Rows
PostgreSQL · Lesson 8 of 120

ORDER BY and LIMIT

Sort, then cut.

⏱ 2 min read▶ Video at 6:12🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Which books cost the most? Rows come back in no particular order, unless you ask. Order by sorts them, and limit keeps the first few.

  • No order by default
  • ORDER BY
  • LIMIT

Most expensive books

Order by price descending puts the highest price first. Title is a tie breaker. Limit keeps five rows. Run it. The five most expensive books.

query.sqlsql
SELECT title, genre, price
FROM books
ORDER BY price DESC, title
LIMIT 5;
Output
          title           |   genre    | price
--------------------------+------------+-------
 Python for Curious Minds | Technology | 34.99
 Data for Everyone        | Technology | 31.99
 SQL in a Weekend         | Technology | 29.99
 Spice Roads              | Cooking    | 27.99
 The Quiet Kitchen        | Cooking    | 24.99
(5 rows)

The next page

Offset skips rows, for the next page of results. Here we skip five and take five. Run it. Books six to ten by price.

query.sqlsql
SELECT title, price
FROM books
ORDER BY price DESC, title
LIMIT 5 OFFSET 5;
Output
          title           | price
--------------------------+-------
 The Pricing Game         | 23.99
 Empires of Salt          | 22.99
 Numbers Don't Lie        | 21.99
 One Pan Dinners          | 21.49
 A Short History of Bread | 19.99
(5 rows)

Summary

Order by sorts, limit keeps the first rows, and offset skips some for paging. Next, missing values.

Key takeaways
  • ORDER BY
  • DESC
  • LIMIT / OFFSET
Next up: NULL and COALESCE — missing values