Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random records

Status
Not open for further replies.

cruel

Programmer
Aug 6, 2001
131
I need to select a given number of random records. I have done this before, about 4 or 5 years ago, I forgot the function name? Anyone? Thanks
 
For example select 6 random records (rownums)
from the all_objects table:

1 select r
2 from ( select r
3 from ( select rownum r
4 from all_objects )
5 order by dbms_random.value )
6* where rownum <= 6
SQL> /

R
----------
7286
17986
9972
9375
3323
10802

6 rows selected.
 
Excess sub query.
Just use:
Code:
select r
              from ( select rownum r
                      from all_objects
             order by dbms_random.value)
    where rownum <= 6;


         R
----------
     35809
     44910
     37879
     13011
      6428
     17288

6 rows selected.

SQL> /

         R
----------
     14144
     31970
     24823
      8509
     43047
     32094

6 rows selected.
 
That is not the way I did it a few years ago. What I eventually want to achieve is to get, say 10 records within each group. For example, 10 random records from model A, another 10 random records from model B, etc. Isn't there a function like random or srand or something? Strange that I could not find it in documentation anywhere. Thanks
 
Post some sample data please and the output you expect or would like.
 
Model QTY
A 10
A 5
...
A 20

B 10
B 5
...
B 20

...

I want to select randomly 2 records from those where model='A' and 2 records from those where model='B'. Thanks
 
Well one obvious way would be to use unions, viz

Code:
select model,qty
              from ( select model,qty
                      from model where model = 'A'
             order by dbms_random.value)
    where rownum <= 2
union
select model,qty
              from ( select model,qty
                      from model where model = 'B'
             order by dbms_random.value)
    where rownum <= 2
 
thanks, but I forgot to mention the list of model is very long. I have plan B (loop) and plan C (combined with other programming language), but they are efficient enough, because the data is very large.
 
OK, try this out:

Code:
select model,qty
from
(
select model,qty,row_number() over (partition by model order by model) r2
from
(
select model,qty
from model
order by model,dbms_random.value
)
) where r2 <= 2
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top