PostgreSQL LIMIT and OFFSET
What is LIMIT?
The LIMIT clause restricts the number of rows returned by a query. It's commonly used for pagination, getting top results, or sampling data.
Basic Syntax
Basic LIMIT Examples
Example 1: Get First N Rows
Example 2: Sample Data
OFFSET Clause
OFFSET skips a specified number of rows before returning results. It's used with LIMIT for pagination.
Basic OFFSET Syntax
OFFSET Examples
Pagination Patterns
Pattern 1: Basic Pagination
Pattern 2: Dynamic Pagination
Pattern 3: Pagination with Total Count
LIMIT with ORDER BY
LIMIT should almost always be used with ORDER BY to ensure consistent results.
Advanced LIMIT Usage
Example 1: Top N per Group
Example 2: LIMIT with Subqueries
Example 3: LIMIT with DISTINCT
LIMIT ALL
LIMIT ALL returns all rows (equivalent to omitting LIMIT):
Performance Considerations
1. Use Indexes with ORDER BY
2. Avoid Large OFFSET Values
3. Keyset Pagination (Seek Method)
More efficient than OFFSET for large datasets:
Common Patterns
Pattern 1: Top N Analysis
Pattern 2: Recent Records
Pattern 3: Random Sampling
LIMIT with JOINs
LIMIT in Subqueries
Practical Examples
Example 1: Dashboard Top Items
Example 2: Leaderboard
Example 3: Preview Data
FETCH Alternative
PostgreSQL also supports the SQL standard FETCH clause:
Common Mistakes and Solutions
Mistake 1: LIMIT Without ORDER BY
Mistake 2: Using LIMIT for Existence Check
Mistake 3: Large OFFSET Performance
Best Practices
- Always Use ORDER BY: Ensure consistent results across queries
- Index ORDER BY Columns: Improve query performance
- Avoid Large OFFSETs: Use keyset pagination for better performance
- Use LIMIT for Testing: Sample data during development
- Consider Total Count: Include total count for pagination UI
- Use FETCH for Portability: FETCH is SQL standard, LIMIT is PostgreSQL-specific
Summary
LIMIT and OFFSET are essential for result set control:
- LIMIT restricts the number of rows returned
- OFFSET skips rows before returning results
- Combine with ORDER BY for consistent results
- Use for pagination, top-N queries, and sampling
- Consider performance with large offsets
- Use keyset pagination for large datasets
- FETCH is the SQL standard alternative to LIMIT
Mastering LIMIT and OFFSET is crucial for building efficient paginated applications and data analysis queries.