SQL ORDER BY and LIMIT
Sorting and limiting turns a long result into a focused top-N list.
SQL tables don't promise a useful row order by themselves. Use
ORDER BY
when the order matters.
Add
DESC
for largest-to-smallest or newest-to-oldest sorting. Then use
LIMIT
when you only need the first few rows.
Without
DESC, the sort runs smallest to largest. That is how a stock report finds what
is about to run out.
select column_one, column_two
from table_name
order by sort_column desc
limit 5 Open the DuckDB playground with the matching dataset and query already filled in.
Schema · Garden Shop Table · products 9 columns · 24 rows
One row per product, with price, cost, and inventory levels.
Show the product name and quantity on hand for the five products with the least stock, lowest first.
Run your query to inspect the result.
Expected answer
- Columns: product_name, quantity_on_hand.
- Rows: 5 products, lowest stock first.
- The first product should be Hanging Basket, with 0 on hand.
That's the last lesson in “Welcome to the Shed.”
The next chapter builds on what this one covered.
Start Chapter 2: Data Types Before Deep Querying → Begins with 2.1 Why data types matterRelated
Clause order and the shape of a SELECT query.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Sort before you limit, or top-N is arbitrary.
Write a first SELECT and read the returned rows.
Return only the columns a report needs, each value once.