PostgreSQL Limit
The LIMIT clause caps how many rows a query returns, which is essential for pagination and quick sampling of large tables.
Limiting Result Rows
LIMIT takes a single number and stops the result set after that many rows have been produced. It's evaluated after WHERE, ORDER BY, and grouping, so it always caps the final output rather than the rows scanned internally.
Returning only the first few rows
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;Pagination with LIMIT and OFFSET
OFFSET skips a given number of rows before LIMIT starts counting, which together let you page through a result set: page one uses OFFSET 0, page two uses OFFSET equal to the page size, and so on. Both keywords are optional and can be used independently.
Paging through results
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 10 OFFSET 20;Combining LIMIT with ORDER BY
LIMIT is only meaningful when paired with a deterministic ORDER BY. Without one, PostgreSQL can return a different subset of rows each time the same query runs, because the underlying row order is not guaranteed.
- Top-N queries: ORDER BY a ranking column, then LIMIT N
- Pagination: ORDER BY a stable key, then LIMIT page_size OFFSET page_size * page_number
- Sampling: LIMIT alone for a quick, non-deterministic peek at a table's shape
A deterministic top-N query
SELECT name, department, salary
FROM employees
ORDER BY salary DESC, name ASC
LIMIT 3;Exercise: PostgreSQL Limit
What does adding LIMIT 5 to a SELECT query do?