Thursday, July 24, 2008

Random numbers in Oracle

Oracle provides a set of neat functions to generate and manipulate random numbers and strings (Yes, random strings!). Here's an example of the generation of a random number:

select dbms_random.random from dual;

Result: 688382086

The following example allows you to limit the generated number between 1 and 1000:

select dbms_random.value(1,1000) num from dual;

Result: 800.627594089089637807565678078832430488

Yikes! This number has a gazillion digits after the decimal point. So let's round it up:

select round(dbms_random.value(1,1000),0) num from dual;

Result: 709


Conclusion:
Random number generation is a useful tool that can have many applications in your SQL code.

A more complete list of things you can do with this is here:
http://www.databasejournal.com/features/oracle/article.php/3341051