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)
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.
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.
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.
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM .
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With