Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of LIMIT for DB2

How do you do LIMIT in DB2 for iSeries?

I have a table with more than 50,000 records and I want to return records 0 to 10,000, and records 10,000 to 20,000.

I know in SQL you write LIMIT 0,10000 at the end of the query for 0 to 10,000 and LIMIT 10000,10000 at the end of the query for 10000 to 20,000

So, how is this done in DB2? Whats the code and syntax? (full query example is appreciated)

like image 811
elcool Avatar asked Oct 07 '10 19:10

elcool


People also ask

Does Db2 support a limit?

2) Using Db2 LIMIT to get top-N rowsThe LIMIT clause is useful to get the top-N report e.g., top 10 books that have the highest rating and top 20 books that have the highest number of pages. In this example: First, sort the books by rating from high to low using the ORDER BY clause.

How do I limit the number of rows in Db2?

Procedure. To limit the number of rows in the result table of a query: Specify the FETCH FIRST n ROWS ONLY clause in the SELECT statement.

How do I SELECT top 10 rows in IBM Db2?

1) Using Db2 FETCH clause to get the top-N rows The ORDER BY clause sorts books by ratings from high to low. The FETCH clause picks only the first 10 rows, which have the highest ratings.

Which database will support the limit clause?

MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM .


1 Answers

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY   FROM EMP   ORDER BY SALARY DESC   FETCH FIRST 20 ROWS ONLY; 

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address FROM (    SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address   FROM contacts   WHERE name LIKE '%Bob%'    ) AS t WHERE t.rid BETWEEN 20 AND 25; 
like image 69
Joe Avatar answered Dec 03 '22 21:12

Joe