Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2 rownum equivalent

Tags:

sql

db2

db2-luw

I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

SELECT * 
FROM  (
   SELECT * 
   FROM db2admin.QUESTION_BANK 
   WHERE type='PROCESS' 
   ORDER BY dbms_random.value
) WHERE rownum <=?

I got alternate for random function but nothing for rownum. Below is query in DB2,

SELECT * 
FROM  (
  SELECT * 
  FROM db2admin.QUESTION_BANK 
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?

The value for rownum is passed via PreparedStatement.

like image 847
Sourav Mehra Avatar asked Apr 16 '26 21:04

Sourav Mehra


2 Answers

DB2 has ROWNUM when you work in the Oracle compatibility mode. To enable just this feature, use this:

db2set DB2_COMPATIBILITY_VECTOR=01
db2stop
db2start

To get all the Oracle features, enable it like this:

db2set DB2_COMPATIBILITY_VECTOR=ORA
db2stop
db2start

The doc on the DB2_COMPATIBILITY_VECTOR has details on alternatives like ROW_NUMBER() OVER().

like image 100
data_henrik Avatar answered Apr 19 '26 09:04

data_henrik


You can use this:

SELECT * 
FROM db2admin.QUESTION_BANK 
WHERE type = 'PROCESS' 
ORDER BY RAND() 
fetch first ? rows only;

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!