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)
Theres these available options:-
Try this
Developed this method:
You NEED a table that has an unique value that can be ordered.
If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:
int start = 40000 - 10000;
int total = 25000 - 10000;
And then pass these by code to the query:
You should also consider the OPTIMIZE FOR n ROWS clause. More details on all of this in the DB2 LUW documentation in the Guidelines for restricting SELECT statements topic:
Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:
See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki
@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:
where
{last}
should be replaced with row number of the last record I need and{length}
should be replaced with the number of rows I need, calculated aslast row - first row + 1
.E.g. if I want rows from 10 to 25 (totally 16 rows),
{last}
will be 25 and{length}
will be 25-10+1=16.