There are two ways to limit the result.
Suppose that you write an application that requires information on only the 10 student with the highest total marks. To return only the rows of the Students table for those 20 student, This can be achived by Fetch First or Limit clause.
Also, This clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.
The Fetch clause allows you to limit the number of rows returned by the query.
SELECT select_list FROM table_name OFFSET n ROWS FETCH {FIRST | NEXT } m {ROW | ROWS} ONLY |
Where,
'n' is the number of rows to skip.
'm' is the number of rows to return. The FIRST and NEXT, ROW and ROWS are interchangeable respectively. They are used for the semantic purpose.
Below is a selection from the "Product" table in the DB2 database.
ProductID | ProductDesc | Category | SRP | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7001 | Mouse | Accessories | 75.00 | ||
7002 | Harddrive | 65.00 | 20 | 1,300 | |
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | RAM | Components | 23.50 | 16 | 376.00 |
7005 | Honda | Bikes | 1,200 | ||
7006 | PEN | 7.45 | 10 | 74.50 | |
7007 | Cddrive | Accessories | 75.00 | ||
7008 | Speaker | Accessories | 75.00 |
The followng SQl query uses the FETCH clause to get the top 4 product in the "Products" table.
SELECT * FROM Product FETCH FIRST 4 ROWS ONLY; |
ProductID | ProductDesc | Category | SRP | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7001 | Mouse | Accessories | 75.00 | ||
7002 | Harddrive | 65.00 | 20 | 1,300 | |
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | RAM | Components | 23.50 | 16 | 376.00 |
To skip the first 2 products and return the next 3 products, We use the FETCH OFFSET clause as follows:
SELECT * FROM Product OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY; |
ProductID | ProductDesc | Category | SRP | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | RAM | Components | 23.50 | 16 | 376.00 |
7005 | Honda | Bikes | 1,200 |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!