Skip to main content
Practice

ORDER BY and LIMIT

When working with data, you might want to sort your results or limit how many rows appear. SQL provides two simple tools for this — ORDER BY and LIMIT.


ORDER BY

The ORDER BY clause is used to sort query 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 order (default): earliest to latest
  • DESC — descending order: newest to oldest

LIMIT

The LIMIT clause controls how many rows are returned in your results.

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

This query displays only the three most recent checkouts.


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.