Tuesday 12 July 2011

Fetching nth row in DB2

Few days back I was facing a problem of fetching a large number of rows (approx.70 000) on a very slow client network. So as a solution I decided to fetch rows in small chunks. In DB2 there is a function  row_number() .
An OLAP function ROW_NUMBER() provides consecutive numbers to rows in a result set .For Example:-
SELECT ROW_NUMBER() OVER(), TABNAME FROM SYSCAT.TABLES WHERE TABSCHEMA='DB2ADMIN'

1 TABNAME
-------------------------------------------
1 CONSECUTIVE_NUMS
2 DATES
3 EXPLAIN_ARGUMENT
4 EXPLAIN_INSTANCE
5 EXPLAIN_OBJECT
6 EXPLAIN_OPERATOR
7 EXPLAIN_PREDICATE
8 EXPLAIN_STATEMENT
9 EXPLAIN_STREAM
10 SALES_DETAIL
11 SALES_DETAIL_CLS
11 record(s) selected.

The query to get rows from 11th to 20th row from a table can be:-


Select EMPID, EMPNAME , DESIGNATION from (
select row_number() over (order by EMPID ASC) as EMPID, EMPNAME , DESIGNATION from Employee_data
)where rownumber BETWEEN 10 and 21;


Reference:    Using DB2 OLAP functions

Please provide your feedback on this post by writing comments on this post below.