SQL LIMIT

Basic LIMIT

This returns only the first 5 rows of the query result.

SELECT * FROM products
LIMIT 5;

LIMIT with ORDER BY

This returns the 3 most expensive products.

SELECT name, price FROM products
ORDER BY price DESC
LIMIT 3;

LIMIT with OFFSET

This skips the first 10 customers and returns the next 5.

SELECT name FROM customers
ORDER BY id
LIMIT 5 OFFSET 10;

Pagination Example

Useful for implementing paging in apps:

-- Page 1 (items 1–10)
SELECT * FROM orders
LIMIT 10 OFFSET 0;

-- Page 2 (items 11–20)
SELECT * FROM orders
LIMIT 10 OFFSET 10;

Best Practices

  • Always sort rows using ORDER BY before applying LIMIT
  • Avoid large OFFSET values in big tables — they can reduce performance
  • Use key-based pagination (e.g., WHERE id > last_id) for efficiency in large datasets

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic