Monday, March 28, 2011

How to generate random numbers in Oracle

You may want to generate random numbers when using Oracle.As many other development tools/languages Oracle also comes with the facility of generating random numbers.

The DBMS_RANDOM package of Oracle will generate random data in character, numeric or alphanumeric formats. The size and the range from which to pickup the random values can also be specified. This package is created by the script dbmsrand.sql available in the <ORACLE_HOME>/rdbms/admin directory.

The following functions present in the package can be used to serve the purpose of generating random numbers and strings. RANDOM - generate random numbers. 

VALUE - generate random numbers from the range provided. The range will be taken as 0-1 if none is provided.

STRING - generate strings in upper case, lower case or alphanumeric format. 

The first parameter takes the string type to be generated, the following values can be provided in upper or lower case.
U - Upper case
L - Lower case
A - Alphanumeric
X - Alphanumeric with upper case alphabets.
P - Printable characters only. 

Examples:

Below are some examples of using the package.

E.g.: Generating a random number (positive or negative)
SQL> select dbms_random.random from dual;

       RANDOM
_____________
   1393936551
E.g.: Generating a random number between 0 and 1.
SQL> select dbms_random.value from dual;

        VALUE
_____________
            1
E.g.: Generating a random number from a range, between 1 to 1000.
SQL> select dbms_random.value(1,1000) num from dual;

          NUM
_____________
          611
E.g.: Generating a 12 digit random number.
SQL> select dbms_random.value(100000000000, 999999999999) num from dual;

          NUM
_____________
 175055628780
E.g.: Generating an upper case string of 20 characters
SQL> select dbms_random.string('U', 20) str from dual;

STR
_______________________
VUOQOSTLHCKIPIADIZTD
E.g.: Generating a lower case string of 20 characters
SQL> select dbms_random.string('L', 20) str from dual;

STR
____________________
xpoovuspmehvcptdtzcz
E.g.: Generating an alphanumeric string of 20 characters. There is a bug in Oracle 8i that results in special (non-alphanumeric) characters such as ']' in the string. This is resolved in Oracle 9i.
SQL> select dbms_random.string('A', 20) str from dual;

STR
__________________
sTjERojjL^OlTaIc]PLB
E.g.: Generating an upper case alphanumeric string of 20 characters
SQL> select dbms_random.string('X', 20) str from dual;

STR
________________________
SQ3E3B3NRBIP:GOGAKSC
E.g.: Generating a string of printable 20 characters. This will output a string of all characters that could possibly be printed.
SQL> select dbms_random.string('P', 20) str from dual;

STR
___________________
*Yw>IKzsj\uI8K[IQPag
If above results comes as fractional values use ROUND function to round up those values:
Eg:
select round(dbms_random.value(100000000000, 999999999999))num from dual;

No comments:

Post a Comment