Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make selecting random rows in oracle faster with table with millions of rows

Tags:

oracle

Is there a way to make selecting random rows faster in oracle with a table that has million of rows. I tried to use sample(x) and dbms_random.value and its taking a long time to run.

Thanks!

like image 945
myeu2 Avatar asked Jun 30 '10 15:06

myeu2


People also ask

How do I randomly select rows in Oracle?

SELECT columns FROM table ORDER BY RAND() LIMIT n; The RAND() function generates a random number between 0 and 1 for each row in the table and the ORDER BY clause will order the rows by their random number.

How do you select a random sample in Oracle?

This is one way to do it: select * from ( select row_number() over(order by dbms_random. value) as random_id, x.


1 Answers

Using appropriate values of sample(x) is the fastest way you can. It's block-random and row-random within blocks, so if you only want one random row:

select dbms_rowid.rowid_relative_fno(rowid) as fileno,
       dbms_rowid.rowid_block_number(rowid) as blockno,
       dbms_rowid.rowid_row_number(rowid) as offset
  from (select rowid from [my_big_table] sample (.01))
 where rownum = 1

I'm using a subpartitioned table, and I'm getting pretty good randomness even grabbing multiple rows:

select dbms_rowid.rowid_relative_fno(rowid) as fileno,
       dbms_rowid.rowid_block_number(rowid) as blockno,
       dbms_rowid.rowid_row_number(rowid) as offset
  from (select rowid from [my_big_table] sample (.01))
 where rownum <= 5

    FILENO    BLOCKNO     OFFSET
---------- ---------- ----------
       152    2454936         11
       152    2463140         32
       152    2335208          2
       152    2429207         23
       152    2746125         28

I suspect you should probably tune your SAMPLE clause to use an appropriate sample size for what you're fetching.

like image 116
Adam Musch Avatar answered Sep 28 '22 06:09

Adam Musch