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. All versions of DB2 provide a mechanism for limiting the records returned from an SQL query with the FETCH FIRST clause. Newer versions of DB2 also support the LIMIT and LIMIT OFFSET clauses. Using the FETCH FIRST syntax or LIMIT syntax (for newer DB2 versions) improves the performance of queries when not all results are required. Listed below are some examples explaining how to use FETCH FIRST and LIMIT / OFFSET.

Example 1: Returning the first 100 rows from a table called employee using the FETCH FIRST syntax:

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

Example 3: Using the LIMIT syntax to fetch the first 10 rows from a table named account:

SELECT * FROM account LIMIT 10

Example 4: Using the LIMIT OFFSET syntax to fetch the first 10 rows from a table named account starting at row 5:

SELECT * FROM account LIMIT 10 OFFSET 5

Many other databases also support limiting rows returned from queries. Listed below are links that show how to limit rows for other popular databases: