Two SQL clauses that often cause confusion are FETCH FIRST N ROWS ONLY and OPTIMIZE FOR N ROWS. While they may sound similar, their purposes are different.
1. FETCH FIRST N ROWS ONLY
- Purpose: Limits the number of rows returned by the query.
- Example:
FETCH FIRST 5 ROWS ONLYreturns exactly 5 rows, even if more qualify. - Use Case: Pagination, top-N queries, or when only a fixed number of rows are needed.
2. OPTIMIZE FOR N ROWS
- Purpose: Influences the optimizer to prioritize fast retrieval of the first N rows.
- Example:
OPTIMIZE FOR 5 ROWSstill returns all qualifying rows but retrieves the first few faster. - Use Case: Interactive applications where users view a small number of rows at a time, allowing incremental processing.
Example Scenario
Suppose an online app displays 5 customer records per screen:
SELECT fname, lname, dept, sal, rollno
FROM dept
ORDER BY sal DESC;
- Index exists on
rollnoand a descending index onsal(with low clustering). - Without
OPTIMIZE FOR, DB2 may perform a tablespace scan + sort onsal. - With
OPTIMIZE FOR 5 ROWS, DB2 uses thesalindex directly to deliver the top 5 rows quickly. Subsequent rows can be fetched incrementally.
Side-by-Side Comparison
| Feature | FETCH FIRST N ROWS ONLY | OPTIMIZE FOR N ROWS |
|---|---|---|
| Limits rows returned | Yes | No |
| Influences optimizer | No | Yes |
| Typical use | Pagination, top-N queries | Interactive applications, incremental fetch |
| Result set | Exactly N rows | All qualifying rows, first N returned faster |
| Effect on access plan | May trigger full table scan + sort | Encourages index usage or plan minimizing response time for first N rows |
✅ Key Takeaway:
- Use
FETCH FIRSTwhen you only want a subset of rows. - Use
OPTIMIZE FORwhen you need fast access to initial rows without limiting the full result set.
Leave a comment