Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do SQL select top N ... in AS400

How do you perform a

Select top N * from as400table 

type query against an as400/db2 database

like image 251
James Moore Avatar asked May 17 '10 15:05

James Moore


People also ask

What does select top 10 do in SQL?

It will return the top number of rows in the result set based on top_value. For example, TOP(10) would return the top 10 rows from the full result set. Optional.

How does top command work in SQL?

The TOP clause allows us to limit the result set of the queries according to the number of rows or the percentage of rows. In general, the TOP and ORDER BY construction are used together. Otherwise, the TOP clause will return the N number of rows in an uncertain order.


2 Answers

Select col1,col2 from  as400table where col1='filter' order by col1 fetch first N row only 

Remember to set an ORDER BY clause, because DB2 does not guarantee that the rows returned by FETCH FIRST N ROW ONLY are always the same N.

like image 53
James Moore Avatar answered Sep 29 '22 07:09

James Moore


Strictly, there is no equivalent of TOP N in DB2.

SELECT 1 FROM sysibm.sysdummy1     WHERE EXISTS (SELECT 2 FROM sysibm.sysdummy1) FETCH FIRST ROW ONLY 

compiles and runs, but

SELECT 1 FROM sysibm.sysdummy1     WHERE EXISTS (SELECT 2 FROM sysibm.sysdummy1 FETCH FIRST ROW ONLY) 

will not compile.

TOP N and FETCH FIRST N are not the same. You can only use FETCH FIRST once per query, whereas TOP N can be used in any sub-select.

You can use a window function in a sub-query in order to simulate TOP N:

select * from (     select id, row_number()     over (order by id) as rn     from testsch.testtbl ) as r where r.rn < 100 -- This is N rows you are looking for 

This will return exactly 99 rows. I tried that in iSeries 7 and it worked.

like image 29
ajeh Avatar answered Sep 29 '22 08:09

ajeh