Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching rows in DB2

Tags:

fetch

db2

I know in DB2 (using version 9.7) I can select the first 10 rows of a table by using this query:

SELECT * 
FROM myTable
ORDER BY id
FETCH FIRST 10 ROWS ONLY

But how can I get, for example, rows 11 to 20? I can't use the primary key or the ID to help me...

Thanks in advance!

like image 284
David Caissy Avatar asked Jul 25 '13 15:07

David Caissy


People also ask

How do you get the first 10 rows in Db2?

To return only the rows of the employee table for those 20 employees, you can write a query as shown in the following example: SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY FROM EMP ORDER BY SALARY DESC FETCH FIRST 20 ROWS ONLY; You can also use FETCH FIRST n ROWS ONLY within a subquery.

What is fetch in Db2?

The fetch-clause sets a maximum number of rows that can be retrieved. It specifies that an application does not want to retrieve more than fetch-row-count rows, regardless of how many rows there might be in the intermediate result table when this clause is not specified.

What is Multi row Fetch in Db2?

The multiple-row FETCH statement can be used to retrieve multiple rows from a table or view with a single FETCH statement. The program controls the blocking of rows by the number of rows requested on the FETCH statement (The Override Database File (OVRDBF) command has no effect.).

How do I use Fetch first?

FETCH FIRST specifies that only integer rows should be made available to be retrieved, regardless of how many rows there might be in the result table when this clause is not specified. An attempt to fetch beyond integer rows is handled the same way as normal end of data.


1 Answers

Here's a sample query that will get rows from a table contain state names, abbreviations, etc.

SELECT *
FROM (
   SELECT stabr, stname, ROW_NUMBER() OVER(ORDER BY stname) AS rownumber
   FROM states
   WHERE stcnab = 'US'
) AS xxx
WHERE rownumber BETWEEN 11 AND 20 ORDER BY stname

Edit: ORDER BY is necessary to guarantee that the row numbering is consistent between executions of the query.

like image 96
Benny Hill Avatar answered Oct 14 '22 22:10

Benny Hill