Using the OPTIMIZE FOR N ROWS clause with the FETCH FIRST N ROWS ONLY clause

The OPTIMIZE FOR n ROWS clause indicates to the optimizer that the application intends to retrieve only n rows, but the query will return the complete result set. The FETCH FIRST n ROWS ONLY clause indicates that the query should return only n rows.

The Db2® data server does not automatically assume OPTIMIZE FOR n ROWS when FETCH FIRST n ROWS ONLY is specified for the outer subselect. Try specifying OPTIMIZE FOR n ROWS along with FETCH FIRST n ROWS ONLY, to encourage query access plans that return rows directly from the referenced tables, without first performing a buffering operation such as inserting into a temporary table, sorting, or inserting into a hash join hash table.

Applications that specify OPTIMIZE FOR n ROWS to encourage query access plans that avoid buffering operations, yet retrieve the entire result set, might experience poor performance. This is because the query access plan that returns the first n rows fastest might not be the best query access plan if the entire result set is being retrieved.