Random number between two integers

Random number between two integers

Though Oracle provides an internal function to generate random numbers, there is no function that gives a random number between any two given integers. Sometimes this is needed to pull random data for test cases. The following function generates a random number between any given two integers. The script is easily updatable to include pulling random_date between two given dates (by converting the date into a Julian date and converting back to date). It has been tested on v. 8.1.7.3.

create or replace function myrand(a IN int,b IN int) 
return number
is
begin
return trunc(abs(( GREATEST(a,b) - LEAST(a,b) + 1 ) * abs(dbms_random.value)) + LEAST(a,b));
end;
/

Here is an example:

1* select myrand(10,20) from dual
SQL> /

MYRAND(10,20)
-------------
18

SQL> select myrand(-1,-20) from dual
2 
SQL> /

MYRAND(-1,-20)
--------------
-16

For More Information

  • Feedback: E-mail the editor with your thoughts about this tip.
  • More tips: Hundreds of free Oracle tips and scripts.
  • Tip contest: Have an Oracle tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize -- submit your tip today!
  • Ask

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

  • the Experts
    :
    Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
  • Forums: Ask your technical Oracle questions--or help out your peers by answering them--in our active forums.
  • Best Web Links: Oracle tips, tutorials, and scripts from around the Web.

This was first published in March 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.

    Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.