How to use LIMIT and OFFSET
· Category: SQL & Databases
Short answer
LIMIT restricts the number of rows returned. OFFSET skips a specified number of rows before returning results, enabling pagination.
Steps
- Top N rows:
SELECT * FROM products ORDER BY price DESC LIMIT 10; - Skip and take:
SELECT * FROM products ORDER BY price DESC LIMIT 10 OFFSET 20; - Page 3 with page size 10:
LIMIT 10 OFFSET 20 - Alternative syntax in SQL Server uses
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY. - Combine with
ORDER BYto ensure deterministic pagination.
Tips
- Always use
ORDER BYwithLIMITandOFFSET; without it, row order is undefined. - Large
OFFSETvalues degrade performance because the database still scans and discards rows.
Common issues
- Offset-based pagination drifts if new rows are inserted between page requests.
- Keyset pagination using
WHERE id > last_seen_idis more efficient for large datasets.r