← Back to all stagesStage 3
Stage 22: LIMIT / OFFSET
Concept
Implement result set pagination so queries can return a subset of matching rows.
What It Teaches
- Early termination: The
LimitNodecallsNext()on its child at most N times, then returns NULL. The executor stops pulling rows — this is the beauty of the Volcano model. - OFFSET skip: The
LimitNodediscards the first M rows by callingNext()without emitting them. - Interaction with ORDER BY:
LIMITwithoutORDER BYreturns an arbitrary subset.ORDER BY ... LIMIT Nreturns the top-N rows. - Efficiency insight: Without a covering index,
LIMIT 10 OFFSET 1000still scans 1010 rows internally. This teaches why cursor-based pagination is preferred in production.
Learning Objectives
- Implement a
LimitNodePlanNode that wraps another node and caps the number of emitted rows. - Support
OFFSET Mto skip M rows before emitting. - Ensure
LIMIT 0returns zero rows (column headers only). - Combine with
ORDER BYfor deterministic top-N queries. - Update the planner to insert
LimitNodewhen LIMIT/OFFSET is present.
New SQL Syntax
SELECT * FROM users LIMIT 5;
SELECT * FROM users LIMIT 5 OFFSET 10;
SELECT * FROM users ORDER BY id DESC LIMIT 3;
Explain Output
[PLAN] SELECT * FROM users ORDER BY id LIMIT 5
[PLAN] └── Limit (count=5, offset=0)
[PLAN] └── Sort (key=id ASC)
[PLAN] └── SeqScan (table=users)