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 BY and LIMIT/OFFSET for effective pagination.
  • Consider performance impacts of large OFFSET values on large datasets.

Key Takeaways

  • LIMIT caps the number of returned rows.
  • OFFSET helps skip a certain number of rows for pagination.