T-SQL Tutorial T-SQL Advanced Database Management T-SQL References

T-SQL RAND() Function



The T-SQL (Transact-SQL) RAND() function returns a random number from 0 through 1, exclusive. The function returns a completely random number if no seed is provided. The function returns a repeatable sequence of random numbers, if seed is provided.

Syntax

RAND(seed)

Parameters

seed Optional. If seed is specified specified, the function returns a repeatable sequence of random numbers. If no seed is specified, it returns a completely random number

Return Value

Returns a random number from 0 through 1, exclusive.

Example:

The example below shows the usage of RAND() function.

/* no seed value is provided,
  hence the result can vary */
SELECT RAND();
Result: 0.5499342331612234

/* 10 is provided as seed value */
SELECT RAND(10);
Result: 0.7137596899542473

/* 0 is provided as seed value */
SELECT RAND(0);
Result: 0.9435973904241444

Random Number in a given Range

The T-SQL (Transact-SQL) RAND() function can be used to create a random number between a given range. For example - to create a random number in a range (a, b), the following formula can be used:

SELECT RAND()*(b-a) + a;

Example:

In the example below, the RAND function is used to create a random number between a range (100, 200).

/* no seed value is provided,
  hence the result can vary */
SELECT RAND()*(200-100) + 100;
Result: 167.5283305591982

/* 10 is provided as seed value */
SELECT RAND(10)*(200-100) + 100;
Result: 171.37596899542473

/* 0 is provided as seed value */
SELECT RAND(0)*(200-100) + 100;
Result: 194.35973904241445

Random Integer in a given Range

The T-SQL (Transact-SQL) RAND() function can be used to create a random integer between a given range. For example - to create a random integer in a range (a, b), the following formula can be used:

SELECT FLOOR(RAND()*(b-a)) + a;

Example:

In the example below, the RAND function is used to create a random integer between a range (500, 600).

/* no seed value is provided,
  hence the result can vary */
SELECT FLOOR(RAND()*(600-500)) + 500;
Result: 557

/* 10 is provided as seed value */
SELECT FLOOR(RAND(10)*(600-500)) + 500;
Result: 571

/* 0 is provided as seed value */
SELECT FLOOR(RAND(0)*(600-500)) + 500;
Result: 594

❮ T-SQL Functions