Skip to content
/ Chapter 1 · Welcome to the Shed
Lesson 1.6 · garden_shop
Lesson 1.6

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.

Pattern
select column_one, column_two
from table_name
order by sort_column desc
limit 5
Ready to run it?

Open the DuckDB playground with the matching dataset and query already filled in.

Schema · Garden Shop Table · products 9 columns · 24 rows
Table · products

One row per product, with price, cost, and inventory levels.

9 columns · 24 rows
product_id int product_name text category_id int supplier_id int price decimal cost decimal quantity_on_hand int reorder_level int discontinued bool
Your task

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.
← Previous · 1.5 Filtering rows with WHERE
End of Chapter 1

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 matter