In this post explains how to use the RAND function in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server (Transact-SQL), the RAND function can be used to return a random number or a random number within a range.
The syntax for the RAND function in SQL Server (Transact-SQL) is:
RAND( [seed] )
Optional. If specified, it will produce a repeatable sequence of random numbers each time that seed value is provided.
To create a random decimal number between two values (range), you can use the following formula:
SELECT RAND()*(b-a)+a;
Where a is the smallest number and b is the largest number that you want to generate a random number for.
SELECT RAND()*(25-10)+10;
The formula above would generate a random decimal number between 10 and 25, not inclusive.
To create a random integer number between two values (range), you can use the following formula:
SELECT FLOOR(RAND()*(b-a+1))+a;
Where a is the smallest number and b is the largest number that you want to generate a random number for.
SELECT FLOOR(RAND()*(25-10+1))+10;
The formula above would generate a random integer number between 10 and 25, inclusive.
The RAND function can be used in the following versions of SQL Server (Transact-SQL):
Let's explore how to use the RAND function in SQL Server (Transact-SQL) to generate a random number between 0 and 1, not inclusive.
For example:
SELECT RAND();
Output: 0.143811355073783 (no seed value, so your answer will vary)
SELECT RAND(9);
Output: 0.713741056982989 (with seed value of 9)
SELECT RAND(-5);
Output: 0.713666525097956 (with seed value of -5)
Let's explore how to use the RAND function in SQL Server (Transact-SQL) to generate a random decimal number between two numbers (ie: range).
For example, the following would generate a random decimal value between 1 and 10, not inclusive (random number would be greater than 1 and less than 10):
SELECT RAND()*(10-1)+1;
Output: 5.09104269717813 (no seed value, so your answer will vary)
SELECT RAND(9)*(10-1)+1;
Output: 7.4236695128469 <strong> (with seed value of 9)
SELECT RAND(-5)*(10-1)+1;
Output: 7.42299872588161 <strong> (with seed value of -5)
Let's explore how to use the RAND function in SQL Server (Transact-SQL) to generate a random integer number between two numbers (ie: range).
For example, the following would generate a random integer value between 10 and 20, inclusive:
SELECT FLOOR(RAND()*(20-10+1))+10;
Output: 19 (no seed value, so your answer will vary)
SELECT FLOOR(RAND(9)*(20-10+1))+10;
Output: 17 (with seed value of 9)
SELECT FLOOR(RAND(123456)*(20-10+1))+10;
Output: 10 (with seed value of 123456)