Reading performance & plans
Concept  ·  SQL & Querying

LIMIT can change the plan; OFFSET pagination re-scans, keyset pagination doesn't.

LIMIT is a row goal — a hint that few rows are wanted — and the optimizer honors it where the pipeline is streamable: scans stop early, ORDER-BY-LIMIT becomes a bounded heap (the TOP_N node keeps the best few without sorting all). It cannot help where the first row depends on all input: aggregates (a hash aggregate builds every group), window functions over full partitions, DISTINCT. The fix lives below the LIMIT: pre-filter, pre-aggregate, or keyset-paginate.

See it break
sightings
namebright
a3
b9
c5
d1
e7
The trap
SELECT
  name
FROM
  sightings
ORDER BY
  bright DESC
;
The fix
SELECT
  name
FROM
  sightings
ORDER BY
  bright DESC
LIMIT
  3;
The trap
b
e
c
a
d
The fix
b
e
c

The full sort returned every sighting when only the brightest 3 were wanted — LIMIT is a row goal the optimizer honors where the pipeline streams (ORDER BY + LIMIT becomes a bounded TOP_N heap), but it can't help an aggregate whose first row needs all input.

The rule

Read the plan for the early-stop node; move selectivity below the limit; keyset for deep pagination.

Shows up elsewhere
Reading a plan for two smellsOFFSET pagination drift
Try one →Prove it in practice →