PostgreSQL LIMIT
The LIMIT clause restricts the number of rows returned by a query. It's often combined with ORDER BY to implement pagination.
Key Topics
1. Basic Syntax
SELECT *
FROM employees
ORDER BY salary DESC
LIMIT 5;
This returns the top 5 results by salary.
2. Using OFFSET
OFFSET skips a specified number of rows before LIMIT takes effect:
SELECT *
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 10;
This skips the first 10 rows and then returns the next 5 rows.
Best Practices
- Combine
ORDER BYandLIMIT/OFFSETfor effective pagination. - Consider performance impacts of large
OFFSETvalues on large datasets.
Key Takeaways
LIMITcaps the number of returned rows.OFFSEThelps skip a certain number of rows for pagination.