SQL Tutorial SQL Advanced SQL Database SQL References

MySQL RAND() Function



The MySQL RAND() function returns a random number between 0 (inclusive) and 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 between 0 (inclusive) and 1 (exclusive).

Example:

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

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

/* 10 is provided as seed value */
mysql> SELECT RAND(10);
Result: 0.6570515219653505

/* 0 is provided as seed value */
mysql> SELECT RAND(0);
Result: 0.15522042769493574

Random Number in a given Range

The MySQL 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 */
mysql> SELECT RAND()*(200-100) + 100;
Result: 143.67012152790102

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

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

Random Integer in a given Range

The MySQL 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 */
mysql> SELECT FLOOR(RAND()*(600-500)) + 500;
Result: 533

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

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

❮ MySQL Functions