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

前端 未结 7 1141
后悔当初
后悔当初 2021-02-13 11:25

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

相关标签:
7条回答
  • 2021-02-13 12:21

    Below Solution to this question is not the exact answer but in many scenarios you try to select a row and try to use it for some purpose and then update its status with "used" or "done" so that you do not select it again.

    Solution:

    Below query is useful but that way if your table is large, I just tried and see that you definitely face performance problem with this query.

    SELECT * FROM ( SELECT * FROM table ORDER BY dbms_random.value ) WHERE rownum = 1

    So if you set a rownum like below then you can work around the performance problem. By incrementing rownum you can reduce the possiblities. But in this case you will always get rows from the same 1000 rows. If you get a row from 1000 and update its status with "USED", you will almost get different row everytime you query with "ACTIVE"

    SELECT * FROM
    ( SELECT * FROM table
    where rownum < 1000
      and status = 'ACTIVE'
      ORDER BY dbms_random.value  )
    WHERE rownum = 1
    

    update the rows status after selecting it, If you can not update that means another transaction has already used it. Then You should try to get a new row and update its status. By the way, getting the same row by two different transaction possibility is 0.001 since rownum is 1000.

    0 讨论(0)
提交回复
热议问题