Skip to main content

LIMIT: Restricting Row Count

LIMIT caps the number of rows returned by a query. This is useful for previewing data and fetching top-N results.

Prior lesson

The sample dataset is defined in the Introduction to SQL lesson.

Syntax

SELECT columns
FROM table_name
ORDER BY column DESC
LIMIT n;

Examples

Example 1: Top 3 orders by value

SELECT
order_id,
customer_id,
total_amount
FROM orders
ORDER BY total_amount DESC
LIMIT 3;

Result:

order_idcustomer_idtotal_amount
11999.00
72999.00
93999.00

Example 2: Most recent 5 orders

SELECT
order_id,
order_date,
total_amount,
status
FROM orders
ORDER BY order_date DESC
LIMIT 5;

Result:

order_idorder_datetotal_amountstatus
102024-05-0124.95pending
92024-04-10999.00pending
82024-04-0189.97completed
72024-03-15999.00completed
62024-03-01349.00cancelled

Common Mistake

LIMIT without ORDER BY is non-deterministic

Without ORDER BY, the database can return any rows - and the selection may differ between runs.

-- Don't do this: which 3 rows you get is undefined
SELECT * FROM orders LIMIT 3;

-- Do this: always pair LIMIT with ORDER BY
SELECT * FROM orders ORDER BY order_id LIMIT 3;

Practice

Write a query that returns the 3 cheapest products (by price), showing name and price.

Show answer
SELECT
name,
price
FROM products
ORDER BY price ASC
LIMIT 3;

Expected result:

nameprice
Notebook4.99
Mouse29.99
Chair199.00
Donate to this project