ORDER BY and LIMIT

Concepts covered: Row Limiting

ORDER BY sets the order of the rows a query returns, and LIMIT sets how many of them come back.

ORDER BY sorts the rows in your result based on one or more columns. By default, sorting is in ascending order (smallest to largest, A to Z). Add DESC after the column name to sort in descending order (largest to smallest, Z to A).

SELECT name, signup_date FROM users ORDER BY signup_date DESC;
Result
namesignup_date
Charlie2025-01-15
Alice2024-11-20
Bob2024-08-05

This returns users sorted by signup date, with the most recent signups appearing first.

Restricting row counts

LIMIT caps how many rows come back, which is what pagination and "top N" queries need.

Pair LIMIT with ORDER BY to get the "top N" results, such as the top 5 customers or the 10 most recent orders.

SELECT name, total_spent FROM customers ORDER BY total_spent DESC LIMIT 3;
Result
nametotal_spent
Global Corp125000
Acme Inc98500
Tech Solutions87200

This returns only the top 3 customers by total spending. Without LIMIT, you would see all customers.

Check your understanding

See if you can combine ORDER BY and LIMIT to answer a common business question.

Combining ORDER BY with LIMIT is the standard pattern for "top N" queries, such as finding the 5 most expensive products or the 10 most recent sign-ups.

Without ORDER BY, the database can return rows in any order it chooses, so LIMIT alone does not guarantee you get the highest or lowest values. It simply returns whichever rows the database finds first.

In large datasets, ORDER BY before LIMIT is much more efficient than sorting the entire result after the fact, because the database can often use an index to avoid scanning every row.

About this lesson

This section is part of the Query Structure: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.