MySQL RAND() Function

The RAND() function in MySQL generates pseudo-random numbers. These are numbers that appear random but are produced by a deterministic algorithm. They are useful for simulations, creating test data, or adding an element of randomness to your applications.



RAND(): Definition and Usage

By default, RAND() produces a different random number each time it's called. However, you can provide a 'seed' value to make the sequence of random numbers repeatable. This is useful for testing or debugging purposes, so you can get the same random numbers in different runs of your code.

Syntax

Syntax

RAND(seed)
      

Parameter Values

Parameter Description
seed (Optional) An integer value used to seed the random number generator. If you provide a seed, you will get the same sequence of "random" numbers each time you run the query. If omitted, a different random number is generated each time.

Examples

Generating a Random Decimal Number (No Seed)

This generates a random decimal number between 0 (inclusive) and 1 (exclusive).

Syntax

SELECT RAND();
      
Output

0.734829 (Example; this will be different each time you run the query)
      

Generating a Random Decimal Number (with Seed)

Using a seed value (6) to generate a repeatable sequence of random numbers.

Syntax

SELECT RAND(6);
      
Output

0.479515 (This will always be the same if you use a seed of 6)
      

Generating a Random Number Between 5 and 10 (exclusive of 10)

Scaling the random number to a specific range.

Syntax

SELECT RAND() * (10 - 5) + 5;
      
Output

(A random decimal number between 5 and 10, excluding 10)
      

Generating a Random Integer Between 5 and 10 (inclusive)

Generating a random integer within a range using FLOOR().

Syntax

SELECT FLOOR(RAND() * (10 - 5 + 1) + 5);
      
Output

(A random integer between 5 and 10, inclusive)
      

**Note:** The outputs for the examples that don't use a seed will change each time the query is run. The example with the seed of 6 will always produce the same output.