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.
SELECT title, checkout_date FROM book_checkouts ORDER BY checkout_date DESC;
ASC
(ascending) is the default: earliest to latestDESC
(descending) sorts from newest to oldest
LIMIT
The LIMIT
clause is used to restrict how many rows are returned in the result set.
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
.
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
Tables
Execution Result