In MySQL, the RAND()
function allows you to generate a random number. Specifically, the function returns a random floating-point value v in the range 0 <= v < 1.0
.
You can also influence the random number by providing a seed value as an argument.
Syntax
The syntax goes like this:
RAND([N])
Where N
is an optional seed value that you can use to influence the result.
Example 1 – No Arguments
Here’s a basic example to demonstrate what happens when we don’t provide an argument.
SELECT RAND();
Result:
+--------------------+ | RAND() | +--------------------+ | 0.4335442291885095 | +--------------------+
The result is not a constant – it will be different each time you run it.
Here’s an example of what happens when we run multiple RAND()
functions together.
SELECT RAND() 'Result 1', RAND() 'Result 2', RAND() 'Result 3';
Result:
+--------------------+---------------------+---------------------+ | Result 1 | Result 2 | Result 3 | +--------------------+---------------------+---------------------+ | 0.9413559538697414 | 0.40614711251682334 | 0.20666773170853753 | +--------------------+---------------------+---------------------+
Example 2 – Using a Seed Value
As mentioned, you can pass in an argument to determine the seed value. This allows you to influence the output of the function.
SELECT RAND(5);
Result:
+---------------------+ | RAND(5) | +---------------------+ | 0.40613597483014313 | +---------------------+
In this case, the function will return the same value each time if an equal argument value is provided.
SELECT RAND(5) 'Result 1', RAND(5) 'Result 2', RAND(5) 'Result 3';
Result:
+---------------------+---------------------+---------------------+ | Result 1 | Result 2 | Result 3 | +---------------------+---------------------+---------------------+ | 0.40613597483014313 | 0.40613597483014313 | 0.40613597483014313 | +---------------------+---------------------+---------------------+
Example 3 – Using RAND() as Part of an Expression
You can use the RAND()
function as part of an expression.
SELECT RAND()*10;
Result:
+-------------------+ | RAND()*10 | +-------------------+ | 8.148973517258627 | +-------------------+
Example 4 – Returning a Random Integer Between Two Numbers
You can combine the RAND()
function with the FLOOR()
function to return a random integer between two numbers.
Here’s how to generate an integer between 5 and 10 (inclusive).
SELECT FLOOR(RAND()*(10-5+1)+5);
Result:
+--------------------------+ | FLOOR(RAND()*(10-5+1)+5) | +--------------------------+ | 7 | +--------------------------+
Let’s run the same code multiple times to see the varying results.
SELECT FLOOR(RAND()*(10-5+1)+5) 'Result 1', FLOOR(RAND()*(10-5+1)+5) 'Result 2', FLOOR(RAND()*(10-5+1)+5) 'Result 3';
Result:
+----------+----------+----------+ | Result 1 | Result 2 | Result 3 | +----------+----------+----------+ | 7 | 9 | 6 | +----------+----------+----------+