Db2 for z/OS & Db2ZAI

Db2 for z/OS and its ecosystem

Connect with Db2, Informix, Netezza, open source, and other data experts to gain value from your data, share insights, and solve problems.

 View Only
  • 1.  Help Request: How to Retrieve all rows matching a WHERE clause, but in "random" order

    Posted Fri June 27, 2025 01:11 PM

    I have a requirement to perform an action against a subset of rows in a DB2 table, i.e. not all rows, but only those that match a WHERE clause. The requirement is to retrieve all of the rows that match the WHERE clause, but in a "random" order. I am thinking I can use a statement like the following

    DECLARE RANDOM_CURSOR FOR

    SELECT rand() as idx, <and other columns)

    WHERE ...

    ORDER BY idx 

    Will this work?

    And do I have to SELECT rand(), and if so, what is its datatype?



    ------------------------------
    Curt Gilker
    ------------------------------


  • 2.  RE: Help Request: How to Retrieve all rows matching a WHERE clause, but in "random" order

    Posted Mon June 30, 2025 12:56 AM

    This might work for you, for the data type RAND return floating point, https://www.ibm.com/docs/en/db2-for-zos/13.0.0?topic=functions-random-rand 

    SELECT NAME FROM (                        
    SELECT RAND(),NAME FROM SYSIBM.SYSTABLES  
    WHERE CREATOR ='SYSIBM'                   
    ORDER BY 1        )                       
    ---------+---------+---------+---------+--
    NAME                                      
    ---------+---------+---------+---------+--
    SYSVIEWDEP_H                              
    SYSDBAUTH                                 
    SYSPACKAUTH_H                             
    SYSCHECKS                                 
    SYSCOLUMNS                                
    DB2_SYSPARM                               
    SYSINDEXPART                              
    SQTCOLUMNS_OLEDB                          
    SYSROUTINEAUTH                            
    SYSCONTROLS_RTXT                          
    SYSVARIABLEAUTH                           
    SYSROUTINES_OPTS                          



    ------------------------------
    Phill Baker
    Software Consultant
    BMC
    ------------------------------



  • 3.  RE: Help Request: How to Retrieve all rows matching a WHERE clause, but in "random" order

    Posted Mon June 30, 2025 11:55 AM

    Thank you Phill - this works!



    ------------------------------
    Curt Gilker
    ------------------------------



  • 4.  RE: Help Request: How to Retrieve all rows matching a WHERE clause, but in "random" order

    Posted Mon June 30, 2025 03:00 PM
    Yes, that should work on DB2 Zos

    DB2 luw has a Random option as part of the Order By Statement


    Sent from my iPhone