Why LIMIT Needs a Meaningful Order

A query limit bounds how many rows can be returned. The chosen order determines which subset a caller sees.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a common list
  2. Inspect the last position
  3. Ask for a particular subset using both order and limit
  4. Test a tie crossing the cutoff

Trace a common list

To show the ten newest articles, order by publication time and an appropriate tie field before taking ten. A limit alone does not specify newest. See ORDER BY with two fields.

Inspect the last position

If two matching articles share the cutoff time, the tie rule determines which appears on the first page. Pagination by offset uses the same boundary choice.[1]

Ask for a particular subset using both order and limit

A query that limits a report to two rows can return any two permitted by execution when no relevant ordering is defined. Sorting by descending score and then ascending ID gives a precise answer even when two rows tie. See stable online result ordering.

WITH jobs(id, score) AS (VALUES (5, 9), (1, 8), (2, 9))
SELECT id FROM jobs ORDER BY score DESC, id ASC LIMIT 2;
-- Expected IDs: 2, 5.

Test a tie crossing the cutoff

With three equal scores, the second sort field decides which two appear. A stable order within a snapshot does not guarantee identical pages during live writes. Verify the list policy separately.

References

  1. PostgreSQL Global Development Group, Queries ↩