Lecture

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

What's Next?

In the next lesson, you'll learn how to remove duplicates and assign custom column names using DISTINCT and AS.

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