RAND Function In SQL

In this blog, we will learn about how to use RAND() function based on our business requirement.
 
So here we will cover the following things:
  • Definition
  • Random Decimal Number
  • Random Integer Range
  • Real example
  • Summary

Definition

 
As the name suggests, the RAND function can be used to return any random number which can be decimal or integer.
 
 
The syntax for the RAND function would be:
  1. SELECT RAND()  
This function will return any random number like this image.
 
RAND Function In SQL 
 

Random Decimal Number

 
We can create any random decimal number between two given numbers, so for that, we can use this formula.
  1. SELECT RAND()*(b-a)+a;  
Here in this formula, you will use b for greater number and a for a lower number, so this formula will return a number between this.
 

Random Integer Range

 
We can create any random integer number between two given numbers, so for that, we can use this formula.
  1. SELECT FLOOR(RAND()*(b-a+1))+a;  
Here in this formula, you will use b for greater number and a for a lower number, so this formula will return a number between this.
 
Note
This RAND() function we can use on the following SQL version, SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005.
 
Real example
 
Now let's see the real example on this function, Here I am using multiple examples so that you can differentiate among them.
 
--//---1- Random Decimal-----//
  1. SELECT RAND()  
  2. SELECT RAND(7);  
  3. SELECT RAND(-7);  
  4. SELECT RAND()*(7-1)+1;  
  5. SELECT RAND(8)*(7-1)+1;  
  6. SELECT RAND(-4)*(7-1)+1;  
--//---2- Random Integer-----//
  1. SELECT FLOOR(RAND()*(8-4+1))+4;  
  2. SELECT FLOOR(RAND(6)*(8-5+1))+5;  
  3. SELECT FLOOR(RAND(123456789)*(10-5+1))+5;  
See this image for result,
 
RAND Function In SQL 
 

Summary

 
Congratulations on following the steps and reaching out here.
 
I hope you liked this tutorial and please share it with others.
 
Thanks for taking your valuable time to read the full article.