Lecture

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
Quiz
0 / 1

What does the following query do?

SELECT * FROM library_members ORDER BY number_of_books DESC LIMIT 2;

Returns all members with fewer than 2 books

Returns the top 2 members who have borrowed the most books

Returns only members with overdue books

Deletes 2 members with most books

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result