PostgreSQL LIMIT Clause
Overview
The LIMIT clause is used to restrict the number of rows returned by a query. It is often used with OFFSET to implement pagination.
Basic Syntax
Simple Examples
LIMIT with ORDER BY
Important: When using LIMIT, you should usually combine it with ORDER BY, otherwise the returned rows are indeterminate.
OFFSET Clause
OFFSET is used to skip a specified number of rows, commonly used for pagination.
Syntax
Pagination Examples
FETCH Clause (SQL Standard)
PostgreSQL also supports the SQL standard FETCH syntax:
FETCH Syntax Variants
Practical Examples
Getting Top N Records
API Pagination Implementation
With Subquery
LIMIT ALL
LIMIT ALL is the same as omitting the LIMIT clause:
Important Notes
Performance Considerations
Indeterminate Results
NULL Value Sorting
Clause Order
Keyset Pagination
For large datasets, keyset pagination is more efficient than OFFSET:
Keyset Pagination Advantages
- Consistent performance, doesn't slow down as page number increases
- Avoids performance issues with large OFFSET values
- Suitable for real-time data and infinite scrolling scenarios