How to Limit Query Results for DB2 Databases

Many times users are only interested in a subset of the results returned from an SQL query. DB2 provides a mechanism for limiting the records returned from an SQL query with the FETCH FIRST command. Using the FETCH FIRST syntax improves the performance of queries when not all results are required. Listed below are some examples explaining how to use FETCH FIRST.

Example 1: Returning the first 100 rows from a table called employee:

select * from employee fetch first 100 rows only

Example 2: Using the fetch first syntax with an order by clause

select * from employee order by salary desc fetch first 10 rows only