ORDER BY and LIMIT
- Version
- 19
- Review
- Draft
Summary#
ORDER BY sorts the result and LIMIT caps the number of rows. Add a unique tie-breaker so paging gives repeatable results for a fixed set of rows.
Syntax#
SELECT column_list
FROM table_name
ORDER BY sort_column DESC NULLS LAST, unique_column DESC
LIMIT page_size OFFSET skipped_rows;
SELECT column_list
FROM table_name
WHERE (sort_column, unique_column) < (last_sort_value, last_unique_value)
ORDER BY sort_column DESC NULLS LAST, unique_column DESC
LIMIT page_size;
SELECT column_list
FROM table_name
ORDER BY sort_column
FETCH FIRST row_count ROWS WITH TIES;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE scores (
id integer PRIMARY KEY,
player text NOT NULL,
score integer
);
INSERT INTO scores (id, player, score) VALUES
(1, 'ana', 91), (2, 'ben', 78), (3, 'cho', 91),
(4, 'dia', NULL), (5, 'eli', 85), (6, 'fay', 78);
-- Page 1. The unique id breaks ties between equal scores.
SELECT id, player, score
FROM scores
ORDER BY score DESC NULLS LAST, id DESC
LIMIT 3;
-- Page 2 by keyset: continue after the last row of page 1 (score 85, id 5).
SELECT id, player, score
FROM scores
WHERE (score, id) < (85, 5)
ORDER BY score DESC, id DESC
LIMIT 3;
-- WITH TIES keeps every row tied with the last one returned.
SELECT player, score
FROM (
SELECT player, score
FROM scores
ORDER BY score DESC NULLS LAST
FETCH FIRST 1 ROW WITH TIES
) AS leaders
ORDER BY player;
ROLLBACK;
Expected output#
id|player|score
3|cho|91
1|ana|91
5|eli|85
(3 rows)
id|player|score
6|fay|78
2|ben|78
(2 rows)
player|score
ana|91
cho|91
(2 rows)
Common mistakes#
LIMIT without an ORDER BY that gives a unique order can return different rows on different runs. A large OFFSET is also costly because the server still computes the skipped rows. Descending order puts nulls first unless you add NULLS LAST. The keyset condition in the example never reaches rows with a null score, so handle those separately if they belong in the pages. WITH TIES compares all sort keys. Apply any unique tie-breaker outside that query if ties should be based on score alone.
Version applicability#
FETCH FIRST ... WITH TIES requires PostgreSQL 13. The LIMIT queries in the example do not depend on that addition.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0