Skip to main content
Practice

ORDER BY and LIMIT

When querying data, you may want to sort the results or limit how many rows are returned. SQL provides 2 powerful tools for this: ORDER BY and LIMIT.


ORDER BY

The ORDER BY clause is used to sort results by one or more columns, in ascending or descending order.

Sort books by checkout date
SELECT title, checkout_date
FROM book_checkouts
ORDER BY checkout_date DESC;
  • ASC (ascending) is the default: earliest to latest
  • DESC (descending) sorts from newest to oldest

LIMIT

The LIMIT clause is used to restrict how many rows are returned in the result set.

Limit results to the 3 most recent checkouts
SELECT title, checkout_date
FROM book_checkouts
ORDER BY checkout_date DESC
LIMIT 3;

This query shows only the 3 most recently checked-out books.


Combining ORDER BY and LIMIT

These two clauses are often combined to answer real questions like:

  • Who borrowed the most books?
  • What were the last 5 books checked out?
  • Show the top 2 most borrowed books.

When do I use ORDER BY and LIMIT?

You can use ORDER BY and LIMIT to:

  • View only the top N results
  • Sort data for reports or dashboards
  • Power features like search ranking or pagination

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.