![]() |
VOOZH | about |
The RAND() function in SQL Server generates pseudo-random floating-point numbers within the range of 0 (inclusive) and 1 (exclusive). It is a function that can produce different random values each time it is called unless a specific seed is provided which results in a repeatable sequence of numbers.
In this article, We will learn about SQL Server RAND() Function in detail with the help of various examples and so on.
RAND() function in SQL Server generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). RAND(), it returns a different random value unless you provide a specific seed.Syntax
RAND() function syntax is:
RAND(seed)RAND() function accepts a parameter as given below:
RAND() is always greater than or equal to 0 and less than 1.RAND() will be repeatable and deterministic.Let's look at some examples of the RAND() function in SQL Server.
In this example, we return a random decimal value.
Query:
SELECT RAND();Output:
0.37892290119984562In this example, we return a random decimal value with seed value =5.
Query:
SELECT RAND(5);Output :
0.71366652509795636In this example, we will use RAND() function with variables and getting a random number between in the range of [ 2, 8 ) using RAND function.
Query:
DECLARE @i INT;
DECLARE @j INT;
SET @i = 2;
SET @j = 8;
SELECT FLOOR(@i + RAND()*(@j-@i));
Output :
7.0This query declares two integer variables, @i and @j, and sets their values to 2 and 8, respectively. It then generates a random floating-point number between @i and @j using the RAND() function, and the FLOOR() function is applied to round down the result to the nearest integer. The final output is a random integer between 2 and 7.
The RAND() function in SQL Server offers a straightforward way to generate random numbers, with the ability to control randomness through seeding. By providing a seed, you can ensure that the sequence of random numbers is reproducible, which is useful for testing and debugging. Without a seed, the function produces non-deterministic results, providing a different random number with each call.