Last Updated: February 25, 2016
· burgatshow

Select a range from SQL table using DB2

It's pretty annoying, that you cannot select a range from a huge SQL table using some simple words like MySQL.

However if you are similar to DB2 and you have the SQL commands at your fingers, a few minutes of thinking can dramatically decrease the amount of code you have to code this feature.

So, what we have in MySQL:

SELECT col1, col2, colN FROM myTable WHERE cond1 = val1 AND cond2 <> val2 ORDER BY col1 LIMIT 0,25

It's very easy. 0 means the first row, and go until you reach 25. But it is working only with MySQL. DB2 twists this a little bit. See the example below if you want to select a range.

DB2 range selection

SELECT col1, col2, colN FROM (SELECT ROW_NUMBER() OVER() AS rownum, myLargeTable.* FROM myLargeTable) AS tmp WHERE rownum > 0 AND rownum <= 25

The range values are just for the example. Anyway if you always have to select only the first N lines, consider of using the syntax below.

First N rows only

SELECT * FROM col1, col2, colN FROM myTable FETCH FIRST 25 ROWS ONLY

Happy coding!

Say Thanks